• 深入理解默认构造函数


    问题描述:

    深入理解C++默认构造函数


    问题解决:

    转载于 http://blog.csdn.net/hankai1024/article/details/7947989


    错误认识1:若程序员没有自己定义无参数的构造函数,那么编译器会自动生成默认构造函数,来进行对成员函数的初始化。

    错误认识2:编译器合成出来的default constructor会明确设定'“class内每一个data member的默认值”。但这两种种认识是有误的,不全面的。

    正确认识:

    默认的构造函数分为有用的和无用的,所谓无用的默认构造函数就是一个空函数、什么操作也不做,而有用的默认构造函数是可以初始化成员的函数。
    对构造函数的需求也是分为两类:一类是编辑器需求,一类是程序的需求。
    程序的需求:若程序需求构造函数时,就是要程序员自定义构造函数来显示的初始化类的数据成员。
    编辑器的需求:编辑器的需求也分为两类:一类是无用的空的构造函数(trivial),一类是编辑器自己合成的有用的构造函数(non-trivival)。

    在用户没有自定义构造函数的情况下:

    一、由于编辑器的需求,编辑器会调用空的无用的默认构造函数。如:类中没有显式定义任何构造函数。

    二、但在某些情况下,编辑器就一定会合有用的默认构造函数。


    1.无关紧要(trivial)的默认构造函数【无用构造函数】

            用户并没有显示地定义默认构造函数,编译器会为它自动生成一个无关紧要(trivial)的默认构造函数,生成的默认构造函数什么也不错,既不会将其成员变量置零,也不会做其他的任何事情,只是为了保证程序能够正确运行而已,这就是所谓的“需要”,如果还需要给初始化成员变量,这件事情还是交给程序员做吧!

    1. #include<iostream> 
    2. using namespace std; 
    3. class Foo 
    4. {  
    5. public:  
    6.   int val;  
    7.   Foo *pnext; 
    8. }; 
    9. void foo_fo(){ 
    10. Foo fo;  
    11. if (fo.val || fo.pnext)  
    12.    {  
    13.       cout << fo.val << endl;  
    14.      cout << fo.pnext << endl;  
    15.    } 
    16. int main() 
    17. {  
    18. foo_fo();  
    19. system("pause");  
    1346905744_9131

    如果基类和继承类都没有自定义的构造函数。那么,都会生成trival的默认构造函数。例:

    1. #include<iostream> 
    2. using namespace std;  
    3. #include<iostream>  
    4. using namespace std;  
    5. class Foo  
    6. {  
    7.   private:  
    8.   int val;  
    9. };  
    10. class Bar:public Foo  
    11. {  
    12. public:  
    13.   char *str;  
    14.   int i;  
    15. };  
    16. void foo_bar()  
    17. {  
    18.    Bar bar;  
    19.    cout<<bar.i<<endl;  
    20. if (bar.str )  
    21. {  
    22.    cout << "Print the content !" << endl; } 
    23. }  
    24. int main()  
    25. {  
    26.   foo_bar();  
    27.   system("pause");  
    28.   return 0;  


    1346908352_8353

    2.非平凡(non-trivival)默认构造函数【有用构造函数】

            C++标准描述了哪些情况,这样的隐式默认构造函数是无关紧要的。一个非平凡(non-trivival)的默认构造函数是ARM中所说的被实现所“需要”,并在必要的时候被编译器自动生成。下面来看看默认构造函数是非平凡的四种情况:


    2.1含有包含默认构造函数的成员类对象

        如果该类包含一个成员类对象,它有默认的构造函数,那么这个类的隐式构造函数是非平凡的,并且编译器需要为包含的这个成员类对象生成一个默认构造函数。然后,这个编译器生成的默认构造函数只有在实际上被调用时才会被真正的生成。如下例中编译器为Bar类生成一个默认构造函数。

    如果一个class中含有成员对象,而且这个对象有default constructor(如Foo foo,Foo类中有default constructor), 那么编译器就会给这个class(Bar)合成一个default constructor, 但是这个合成动作只有在调用需要时才会产生。也就是说,在需要时才会合成。

    1. #include<iostream>  
    2. using namespace std;  
    3. class Foo  
    4. {  
    5. public:  
    6.   Foo();  
    7.   Foo( int ); 
    8. private:   
    9.   int val;  
    10. };  
    11. Foo::Foo()  
    12. {  
    13.   cout << "Call Foo::Foo() Constructor !"<< endl;  
    14.   val = 0;  
    15. }  
    16. Foo::Foo(int i)  
    17. {  
    18.   cout << "Call Foo::Foo(int i) Constructor !"<< endl;  
    19.   val = i;  
    20. }  
    21. class Bar  
    22. {  
    23. public
    24.   Foo foo;  
    25.   char *str;  
    26. }; 
    27. void foo_bar()  
    28. {  
    29.   Bar bar; // Bar::foo must be initialized here if (bar.str )  
    30.   { cout << "Print the content !" << endl; }  
    31. }  
    32. int main()  
    33. {  
    34.   foo_bar();  
    35.   system("pause");  
    36.   return 0;  

    1346847998_3322

        在这个程序片段中Bar的成员foo含有默认构造函数,它初始化自己的类成员val为0而Bar本身并没有定义默认的构造函数,这个构造函数的目的是为了初始化它的成员变量foo,实际上就是调用Bar::foo的默认构造函数,但它并不会做一丁点关于另外一个变量str的初始化和赋值工作,初始化Bar::foo是编译器的责任,二初始化str是程序员的责任。

    我们可以用以下代码来大致描述一下编译器的工作:

    1. inline Bar::Bar() { // Pseudo C++ Code foo.Foo::Foo(); } 

    结论:如果class中内含一个以上的含有default constructor的object,那在为class合成的default constructor中,会按照object的声明次序调用object 的 default constructor

    如果Bar中用户自定义的默认构造函数(用户有定义,则编译器不会再自动生成,编译器会扩充已存在的constructors 在其中安插一些代码,使得在用户代码被执行之前,先调用必要的default constructors ):

    1. #include<iostream>  
    2. using namespace std; 
    3. class Foo  
    4. {  
    5. public:  
    6.   Foo();  
    7.   Foo( int );  
    8. private:  
    9.   int val;  
    10. }; 
    11. Foo::Foo()  
    12. {  
    13.   cout << "Call Foo::Foo() Constructor !"<< endl;  
    14.   val = 0;  
    15. }  
    16. Foo::Foo(int i)  
    17. {  
    18.   cout << "Call Foo::Foo(int i) Constructor !"<< endl;  
    19.   val = i;  
    20. }  
    21. class Bar  
    22. {  
    23. public:  
    24.   Foo foo;  
    25.   char *str;  
    26.   Bar(){}//默认构造函数  
    27. };  
    28. void foo_bar()  
    29. {  
    30.   Bar bar;  
    31. if (bar.str ) { 
    32.   cout << "Print the content !" << endl;  
    33. }  
    34. }  
    35. int main()  
    36. {  
    37.   foo_bar();  
    38.   system("pause"); 
    39.   return 0;  

    结果一样:

    1346907036_7557


    以上派生类Bar扩充构造函数如下:

    //扩张后的default constructor

    Bar::Bar()

    {

        foo.Foo::Foo();

    }


    对比,以下代码不符合上述要求,会报错:

    1. #include<iostream>  
    2. using namespace std;  
    3. class Foo  
    4. {  
    5. public:  
    6.   Foo(); //去掉默认构造函数会报错  
    7.   Foo( int );  
    8. private:  
    9.   int val; 
    10. };  
    11. Foo::Foo()  
    12. {  
    13.   cout << "Call Foo::Foo() Constructor !"<< endl;  
    14.   val = 0;  
    15. }  
    16. Foo::Foo(int i)  
    17. {  
    18.   cout << "Call Foo::Foo(int i) Constructor !"<< endl;  
    19.   val = i;  
    20. }  
    21. class Bar  
    22. {  
    23. public:  
    24.   Foo foo(1); //不是默认构造函数产生的成员,也会报错。expected `;' before '(' token char *str;  
    25. };  
    26. void foo_bar()  
    27. {  
    28.   Bar bar; // Bar::foo must be initialized here  
    29. if (bar.str )  
    30. {  
    31.   cout << "Print the content !" << endl; }  
    32. }  
    33. int main()  
    34. {  
    35.   foo_bar();  
    36.   system("pause");  
    37.   return 0;  
    38. }  
    注意:如果Bar含有多个成员类变量,则编译器会按照这些变量的声明顺序去做以上处理。例:
     
    clipboardclipboard
     
    1346907435_6823
     
     

    2.2 一个类的父类自定义的无参构造函数(有non-trival的默认构造函数)

    父类有自定义的默认构造函数,子类无任何自定义构造函数

    1. #include<iostream>  
    2. using namespace std;  
    3. class Foo  
    4. {  
    5. public:  
    6.   Foo()  
    7.   {  
    8.     cout << "Call Foo::Foo() Constructor !"<< endl;  
    9.     val = 0;  
    10.   }  
    11.   Foo(int i)  
    12.   {  
    13.     cout << "Call Foo::Foo(int i) Constructor !"<< endl;  
    14.     val = i;  
    15.    }  
    16. private:  
    17.   int val;  
    18. };  
    19. class Bar:public Foo  
    20. {  
    21. public: //Foo foo;  
    22. char *str;  
    23. };  
    24. void foo_bar()  
    25. {  
    26.   Bar bar;  
    27.   if (bar.str )  
    28.   {  
    29.   cout << "Print the content !" << endl;  
    30.   }  
    31. }  
    32. int main()  
    33. {  
    34.   foo_bar();  
    35.   system("pause");  
    36.   return 0;  


    1346908586_3339

     

    如果一个没有任何constructor的派生类继承自一个带有default constructor(用户定义的)的base class, 那么这个派生类的default constructor被认为是nontrivial,而对于nontrivial的default constructor, 编译器会为他合成出来。在合成出的default constructor中调用base class的default constuctor.

         如果设计者提供了多个constructor,但为提供default constuctor,那编译器不会合成新的default constructor,而是会扩展所有的现有的constructor,安插进去default constructor所必须的代码。如果此类中仍存在第一种情况,也就是说存在有menber object, 而且object含有default constructor, 那这些default constructor 也会被调用,在base class的default constructor被调用后。

    如果把//Foo foo这句也加上,结果为:

    1346908671_7145 

       

        因为在创建子类对象时需要调用父类的构造函数,同时,由于子类包含父类成员对象,初始化成员对象时也需要调用父类构造函数。


    2.3 一个类里隐式的含有Virtual tabel(Vtbl)或者pointer member(vptr),并且其基类无任何构造函数或者有用户自定义的默认构造函数。

      

         vtbl或vptr需要编辑器隐式的合成出来,那么编辑器就把合成动作放在了默认构造函数里,所以编辑器必需自己产生一个构造函数来完成这些动作。所以你的类里只要含有virtual function,那么编辑器就会生成默认的构造函数。

        无论一个class是声明(或继承)了一个virtual function, 还是派生自一个继承串联,其中有一个或多个virtual base class.不管上述哪种情况,由于缺乏由user声明的constructor, 编译器会详细记录合成一个default constructor的详细信息。

     在编译期间,会做以下的扩张工作:

    (1) 一个virtual function table会被编译器产生出来,内含virtual functions的地址。

    (2) 编译器会合成一个vptr, 插入每一个object中。

    而合成出来的default constructor,当然会为每一个object 设定vptr的初值。但不会为类的成员变量初始化。

    例,基类有虚函数,并且无构造函数或者有用户自定义的默认构造函数:

     

    clipboard

    clipboard

    1346916027_4202

    例:基类为抽象类,且无构造函数。

    1. #include<iostream> 
    2. using namespace std; 
    3. class Widget 
    4. public:  
    5.     virtual void flip() = 0; 
    6. }; 
    7. class Bell: public Widget 
    8. public:  
    9.   void flip() 
    10.   {  
    11.     cout <<"Bell." << endl;  
    12.    } 
    13. }; 
    14. class Whistle: public Widget 
    15. public:  
    16.   void flip() 
    17.   {  
    18.    cout <<"Whistle." << endl; } 
    19.   }; 
    20. void flip(Widget &widget) 
    21. {  
    22.    widget.flip(); 
    23. void foo() 
    24. {  
    25.   Bell b;  
    26.   Whistle w;  
    27.   flip(b);  
    28.   flip(w); 
    29. int main() 
    30. foo();  
    31. system("pause"); 

    1346916218_7041


    2.4 如果一个类虚继承与其他类

        理由和2.3一样,虚基类也需要vtbl和vptr管理,那么这些管理就需要合成构造函数来实现管理,则需要生成默认的构造函数。

    例:

    1. #include<iostream> 
    2. using namespace std; 
    3. class Base 
    4. {  
    5. public:  
    6.   int x;  
    7. void set()  
    8. {  
    9.   cout<<"Base set"<<endl;  
    10.   cout<<x<<endl;  
    11. }  
    12. }; 
    13. class Derived1:virtual public Base 
    14. {  
    15. public:  
    16.   int y;  
    17. void set()  
    18. {  
    19.   cout<<"Derived1 set"<<endl;  
    20.   cout<<y<<endl;  
    21. }  
    22. }; 
    23. class Derived2:virtual public Base 
    24. {  
    25. public:  
    26. int z;  
    27. void set()  
    28. {  
    29. cout<<"Derived2 set"<<endl;  
    30. cout<<z<<endl;  
    31. }  
    32. }; 
    33. int main() 
    34. {  
    35. Base b;  
    36. b.set();  
    37. Derived1 d1;  
    38. d1.set();  
    39. Derived2 d2;  
    40. d2.set();  
    41. system("pause");  

    1346916965_8163

    与如下代码效果一样:

    1. #include<iostream>
    2. using namespace std;
    3. class Base
    4. {
    5. public:
    6. int x;
    7. Base()//用户定义的默认构造函数 {}
    8. Base(int i)//用用户定义的含参构造函数
    9. { x=i; }
    10. void set()
    11. {
    12. cout<<"Base set"<<endl;
    13. cout<<x<<endl;
    14. }
    15. };
    16. class Derived1:virtual public Base
    17. {
    18. public:
    19. int y;
    20. void set()
    21. {
    22. cout<<"Derived1 set"<<endl;
    23. cout<<y<<endl;
    24. }
    25. };
    26. class Derived2:virtual public Base
    27. {
    28. public:
    29. int z;
    30. void set()
    31. {
    32. cout<<"Derived2 set"<<endl;
    33. cout<<z<<endl;
    34. }
    35. };
    36. int main()
    37. {
    38. Base b;
    39. b.set();
    40. Derived1 d1;
    41. d1.set();
    42. Derived2 d2;
    43. d2.set();
    44. system("pause");
    45. }

    3.当用带有默认参数的构造函数进行初始化的时候,可以用类似默认参数初始化类的对象的方式来进行初始化。

    特别注意:以下所有情况均为把有参构造函数用默认值初始化的特例(长得像,但并不是默认构造函数),并非有默认构造函数。创建对象方式与默认构造函数相同,但意义不一样。以下是在声明时成员初始化为0,则调用形式与默认构造函数相同。其本质是使用带

    例1:父类无构造函数(有编译器自己创建的trival型的),子类已经有有参构造函数。生成对象的时候实际调用的是有参构造函数,只不过参数都是0,可以省略不写。

    1. #include<iostream>
    2. using namespace std;
    3. class Point
    4. {
    5. protected:
    6. int x0,y0;
    7. public:
    8. void set()//或者virtual void set()
    9. { cout<<"Base"<<endl; }
    10. };
    11. class Derived:public Point
    12. { protected:
    13. int x1,y1;
    14. public:
    15. Derived(int m=0,int n=0)
    16. { x1=m; y1=n; }
    17. void set()
    18. {cout<<"Derived_set()"<<endl;}
    19. void draw(){cout<<"Derived_draw()"<<endl;}
    20. };
    21. void test(Point *b){ b->set(); }
    22. int main()
    23. {
    24. Derived *dr=new Derived;
    25. test(dr);
    26. Derived drr;
    27. test(&drr);
    28. system("pause");
    29. }

    1346849562_8676

    如果是

    virtual void set()

    则结果为:

    1346849665_8475


    例2:基类含无参构造函数,子类已经有有参构造函数。

    1. #include<iostream>
    2. using namespace std;
    3. class Point
    4. {
    5. protected:
    6. int x0,y0;
    7. public:
    8. void set()
    9. { cout<<"Base"<<endl;
    10. }
    11. Point(){//基类无参构造函数
    12. }
    13. };
    14. class Derived:public Point
    15. {
    16. protected:
    17. int x1,y1;
    18. public:
    19. Derived(int m=0,int n=0)
    20. { x1=m; y1=n; }
    21. void set(){cout<<"Derived_set()"<<endl;}
    22. void draw(){cout<<"Derived_draw()"<<endl;}
    23. };
    24. void test(Point *b)
    25. {
    26. b->set();
    27. }
    28. int main()
    29. {
    30. Derived *dr=new Derived;
    31. test(dr);
    32. Derived drr;
    33. test(&drr);
    34. system("pause");
    35. }

    结果:

    1346850378_3652

    例3:基类含有参构造函数

    1. #include<iostream> 
    2. using namespace std; 
    3. class Point 
    4. {  
    5. protected:  
    6. int x0,y0;  
    7. public:  
    8. void set()  
    9. { cout<<"Base"<<endl; }  
    10. Point(int i,int j) 
    11. { x0=i; y0=j; }  
    12. };  
    13. class Derived:public Point  
    14. {  
    15. protected: int x1,y1;  
    16. public:  
    17. Derived(int m=0,int n=0,int i=0,int j=0):Point(i,j)  
    18. { x1=m; y1=n; }  
    19. void set() 
    20. {cout<<"Derived_set()"<<endl;}  
    21. void draw() 
    22. {cout<<"Derived_draw()"<<endl;}  
    23. }; 
    24. void test(Point *b) 
    25. { b->set(); } 
    26. int main() 
    27. {  
    28. Derived *dr=new Derived;  
    29. test(dr);  
    30. Derived drr;  
    31. test(&drr);  
    32. system("pause");  

    结果:

    1346850560_3405

    例4:对于基类含有虚函数和抽象类也和上面所说的情况一致。

    1. #include<iostream> 
    2. using namespace std; 
    3. class Point 
    4. {  
    5. protected:  
    6. int x0,y0;  
    7. public:  
    8. Point(int i,int j)  
    9. { x0=i; y0=j; }  
    10. virtual void set()=0;  
    11. virtual void draw()=0;  
    12. }; 
    13. class Line:public Point 
    14. {  
    15. protected: int x1,y1;  
    16. public: Line(int i=0,int j=0,int m=0,int n=0):Point(i,j)  
    17. { x1=m; y1=n; }  
    18. void set() 
    19. {cout<<"Line_set()"<<endl;}  
    20. void draw(){cout<<"Line_draw()"<<endl;}  
    21. }; 
    22. class Ellipse:public Point 
    23. {  
    24. protected:  
    25. int x2,y2;  
    26. public:  
    27. Ellipse(int i=0,int j=0,int p=0,int q=0):Point(i,j)  
    28. { x2=p; y2=q; }  
    29. void set() 
    30. {cout<<"Ellipse_set()"<<endl;}  
    31. void draw() 
    32. {cout<<"Ellipse_draw()"<<endl;}  
    33. }; 
    34. void drawobj(Point *p) 
    35. {  
    36. p->draw();  
    37. void setobj(Point *p) 
    38. { p->set(); } 
    39. int main() 
    40. {  
    41. Line *li=new Line();//new Line;  
    42. drawobj(li);  
    43. setobj(li);  
    44. cout<<endl;  
    45. Ellipse *el=new Ellipse();//new Ellipse;  
    46. drawobj(el);  
    47. setobj(el);  
    48. cout<<endl;  
    49. Line *li2=new Line;  
    50. drawobj(li2);  
    51. setobj(li2);  
    52. cout<<endl;  
    53. Ellipse elp;  
    54. drawobj(&elp);  
    55. setobj(&elp);  
    56. cout<<endl;  
    57. system("pause");  

    1346852092_4791

  • 相关阅读:
    【html+table】基于jQuery,利用TableFreeze.js实现html的table冰冻效果,非常强大
    vue中使用element-ui实现excel表格导入
    正则第二次配结果与第一次不一致;正则匹配,第一次匹配结果正常,第二次匹配结果就错误,第三次又正常,第四次又错误,以此类推
    关于用vsCode格式化代码时,代码自动换行问题
    百度地图实现测量面积和测量距离功能
    sql 通过group by、sum聚合查询结果的排序
    C#小数计算的坑
    C# 反射的例子
    IE8环境下的上传图片预览
    做移动端电子签名发现canvas的 一些坑
  • 原文地址:https://www.cnblogs.com/luosongchao/p/3381602.html
Copyright © 2020-2023  润新知