继承时的初始化列表

来源:互联网 发布:快说话配音软件 编辑:程序博客网 时间:2024/06/05 17:46

问题引出:

class Test{public:                 Test(int a, int b)                {                                 this->a = a;                                 this->b = b;                }private:                 int a ;                 int b ;};class TChild :public Test{public:private:};void main (){                TChild B ;                 system("pause" );}

在定义TChild类的对象时,要调用父类的构造函数,那父类只有有参的构造函数,所以必须要使用构造函数的初始化列表。

问题的解决:

class Test{public :                 Test (int a, int b)                {                                 this ->a = a;                                 this ->b = b;                }                 void getTest ()                {                                 cout << a << "  "<< b << endl ;                }private :                 int a ;                 int b ;};class TChild : public Test{public :                 TChild (int x, int y) : Test( x, y)  //使用初始化列表                {                }private :};void main (){                 TChild A (1,2);                 A .getTest ();                 system ("pause" );}

这里写图片描述

0 0
原创粉丝点击