In C ++, struct has the "class" function. The difference between struct and the keyword class is that the default access permission for member variables and functions in struct is public, while the class is private.
For example, define the struct Class and Class class:
Struct structa
{
Char;
...
}
Class classb
{
Char;
...
}
Then:
Struct a;
A. A = 'a'; // access the public member, valid
Classb B;
B. A = 'a'; // access the private member, invalid
Many documents have written here that all the differences between struct and class in C ++ have been given. In fact, it is not true. Note that:
Struct in C ++ maintains full compatibility with struct in C (which complies with the original intention of C ++-"A Better C"). Therefore, the following operations are legal:
// Define struct
Struct structa
{
Char;
Char B;
Int C;
};
StructA a = {'A', 'A', 1}; // assign the initial value directly when defining
That is, struct can assign an initial value to the member variable {} directly during definition, while the class cannot, the author emphasizes this point in the classic bibliography thinking C ++ 2nd edition.
4. Precautions for struct Programming
Take a look at the following program:
1. # include <iostream. h>
2. struct structA
3 .{
4. int iMember;
5. char * cMember;
6 .};
7. int main (int argc, char * argv [])
8 .{
9. structA instant1, instant2;
10. char c = 'a ';
11. instant1.iMember = 1;
12. instant1.cMember = & c;
13. instant2 = instant1;
14. cout <* (instant1.cMember) <endl;
15. * (instant2.cMember) = 'B ';
16. cout <* (instant1.cMember) <endl;
17. return 0;
}
The output result of the 14 rows is:
The output result of 16 rows is: B
Why? The modification to instant2 in row 15 changes the value of the Member in instant1!
The reason is that the value assignment statement of instant2 = instant1 in row 13 adopts the copy of variables one by one, which enables the cMember in instant1 and instant2 to point to the same disk memory, therefore, modifications to instant2 are also modifications to instant1.
In the C language, when the struct contains pointer members, be sure to use the value assignment statement to determine whether to direct the pointer members of the two instances to the same memory.
In C ++, when the struct contains pointer-type members, we need to override the copy constructor of struct and reload the "=" operator.