|
|
|
Struct Examples
C/C++ has a user defind data structure called a struct. A struct is
similar to a class except that structs do not have member functions and there
is no concept of private members.
1. A Music_rec struct
% cat struct0.cpp
// struct example
#include <iostream>
#include <iomanip>
using namespace std;
#include<string>
struct Music_rec
{
string comp;
string title;
int id;
};
int main()
{
int i;
Music_rec myCD = {"Mozart", "The Magic Flute", 786};
cout << myCD.comp << " " << myCD.title
<< " " << myCD.id
<< endl;
myCD.comp = "Stravinsky";
myCD.title = "The Rite of Spring";
myCD.id = 111;
cout << myCD.comp << " " << myCD.title
<< " " << myCD.id
<< endl;
return 0;
}
% g++ struct0.cpp
% a.out
Mozart The Magic Flute 786
Stravinsky The Rite of Spring 111
2. An array of Music_rec structs
% cat struct1.cpp
// struct example
#include <iostream>
#include <iomanip>
using namespace std;
#include<string>
const int NUMRECS = 4;
struct Music_rec
{
string comp;
string title;
int id;
};
int main()
{
int i;
Music_rec musicList[NUMRECS] = {
{"Bach","Air on a G String", 389},
{"Mozart", "The Magic Flute", 786},
{"Sibelius", "Finlandia", 985},
{"Stravinsky","The Rite of Spring", 123}
};
cout << setiosflags(ios::left);
for( i = 0; i < NUMRECS; i++ )
cout << setw(12) << musicList[i].comp
<<
setw(30) <<musicList[i].title
<<
setw(6) <<musicList[i].id
<<
endl;
return 0;
}
% g++ struct1.cpp
% a.out
Bach Air on a G
String
389
Mozart The Magic
Flute
786
Sibelius
Finlandia
985
Stravinsky The Rite of Spring
123
|
|