[C ++ primer] in-depth analysis of struct-interview FAQ

Source: Internet
Author: User

I. deep differences between struct and C ++

1) 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 A; // The default value is private.
...
}

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:


Struct structa
{
Char;
Char B;
Int C;
};

Structa A = {'A', 'A', 1}; // assign the initial value directly when defining

That is, struct can directly assign an initial value to its member variable at the time of definition, while struct cannot.


2) In C, struct cannot contain functions. In C ++, struct is expanded to include functions.

# Include "stdio. H "Void fun () {printf (" Hello, world ") ;}struct test {void (* Fun) () ;}; int main () {struct test _ t; _ T. fun = fun; // You must assign the address of a function to the member function of the structure (* _ T. fun) (); // call the function return 0 through the function address ;}

The above program runs correctly. If the function is included in the structure, the implementation will not work. For example:

# Include struct test {void fun () {printf ("Hello, world") ;}// not allowed}; int main () {struct test _ t; _ T. fun (); Return 0 ;}

3) The structure struct in C ++ can contain constructors.

#include <iostream>using namespace std;void Fun();struct test{       test(int n){                    cout<<"test("<<n<<")"<<endl;       }       test(){           cout<<"test()"<<endl;}      void (*Fun)();  };  void Fun(){    cout<<"Fun()"<<endl;         // printf("Fun()\n");      }    int main()  {      test a(1);      a.Fun=Fun;      (*a.Fun)();            return 0;   }

4) struct Nesting Problem (C language)

#include "stdio.h"typedef struct   test2{         int   aa;         int   bb;}test2;typedef struct   test1{    test2 t;        }test1;int main(){              printf("%d\n",sizeof(test1));            return 0; }

Output: 8

Another expression

# Include "stdio. H "typedef struct test1 {struct Test2 {int AA; int BB;} Test2; // note that if no variable exists, sizeof is 1} test1; int main () {printf ("% d \ n", sizeof (test1); Return 0 ;}


2. 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 // The change is instant2. How has instant1 also been changed?

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 usesCopy variables one by one, Which makes the cmember in instant1 and instant2Pointing to the same disk memorySo the modification to instant2 is also the modification 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.

III. For details about size alignment, refer

Struct memory alignment

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.