|
Simple structures in C++ look very much like structures in C. For example, we could declare User to be a C++ structure by
struct User { //(A) string name; int age; };
In C, the identifier User is called a structure tag that can be used to declare a variable, say, u1, to be of type struct User by
struct User u1;
However, in C++, User is a new type name directly. And we can say
User u1, u2;
if we wish to declare the variables u1 and u2 to be of type User.
A structure in C++ can be thought of as a light-weight C++ class. We can use the dot (.) or the member-access operator (->) to access the members of a structure, as in
void f() { //(B) User u; u.name = Orpheus; u.age = 89; User* p = new User(); p->name = Ophelia; p->age = 21; }
This function first creates a new user, u, whose name is Orpheus and age 89, the rest of the members, if any, remaining uninitialized. Next, the function creates another User with the name and the age fields initialized to Ophelia and 21, respectively.
One can even embed functions inside the definition of a C++ structure. We could expand the definition of the User structure in line (A) above and include a print() function in it:
struct User { string name; int age; void print() { cout << "User" << name << "is of age" << age << endl; } };
Now suppose u is a User. We can invoke its print method by
u.print();
We can even engage in data hiding by declaring private some of the members of a structure. The default access privilege of a structure member is public, which is the opposite of what it is for a class. In the following example, we have declared the two data members to be private. Of course, with private data members, we'd also need to provide the structure with a constructor, as in line (C) below:
struct User { private: string name; int age; public: //constructor: User( string s1, int yy ) { name = s1; age = yy; } //(C) void print() { cout << User << name << is of age<< age << endl; } };
With a constructor provided in this manner, we can use the same syntax as with classes for constructing objects from a C++ structure:
User u( "Zaphod", 27 ); User* p = new User( "Beeblebrox", 16 );
The following example shows a particularly quick way to initialize a small array of structures.
//StructInit.cc #include <iostream> using namespace std; struct User { char* name; int age; short rank; }; void print( User*, int ); int main() { User usr_list[] = { //(A) "Bigshot, I. R. ", 39, 1, "Allears, U. B, ", 29, 100, "Moonstruck, H. I.", 58, 45 }; int size = sizeof( usr_list ) / sizeof( usr_list[0] ); print( usr_list, size ); return 0; } void print( User* up, int n ) { for ( int i=0; i < n; i++ ) cout << up[i].name << '\t' << up[i].age << '\t' << up[i].rank << ’\n’; }
The initializer provided to the array declaration in line (A) consists simply of a sequence of comma-separated values for each data member for all the elements of the array. The compiler automatically figures out the size of the array—in this case 3.
|