您的位置:首页 > 其它

关于nontrivial default constructor(二)

2017-03-01 19:38 267 查看

情况一:

如果一个没有任何构造函数的class派生自一个带有默认构造函数的base class,那么派生类的构造函数被视为nontrivial,因此会被编译器合成出来。它将调用基类的默认构造函数。
class Base
{
public:
Base()
{
cout << "Base constructor ..." << endl;
}
};

class Derived : public Base
{
public:

};

int main(void)
{
Derived derived;
return 0;
}
结果如下:
                                

   
    

情况二:

如果设计者提供多个构造函数,但就是没有default constructor, 编译器会扩张每一个构造函数。但它不会合成一个新的默认构造函数。
class Base
{
public:
Base()
{
cout << "Base constructor ..." << endl;
}
};

class Derived : public Base
{
public:
int a;
Derived(int x)
{
a = x;
}
};

int main(void)
{
//Derived derived;    //出现编译错误
Derived derived(10);
cout<<derived.a<<endl;
return 0;
}



当然,如果此时定义了默认构造函数,如下,
class Base
{
public:
Base()
{
cout << "Base constructor ..." << endl;
}
};

class Derived : public Base
{
public:
int a;
Derived(int x)
{
a = x;
}
Derived()
{
cout<<"user-defined default constructor ..."<<endl;
a = 0;
}
};

int main(void)
{
Derived derived0;
cout<<derived0.a<<endl;
Derived derived1(10);
cout<<derived1.a<<endl;

return 0;
}



如果类内还存在着带有默认构造函数的member class object,则这些默认构造函数也会被调用——在基类构造函数之后
class Base
{
public:
Base()
{
cout << "Base constructor ..." << endl;
}
};

class B
{
public:
B()
{
cout << "B constructor ..." << endl;
}
};
class Derived : public Base
{
public:
int a;
B b;
Derived(int x)
{
a = x;
}
Derived()
{
cout<<"user-defined default constructor ..."<<endl;
a = 0;
}
};

int main(void)
{
Derived derived0;
cout<<derived0.a<<endl;
Derived derived1(10);
cout<<derived1.a<<endl;

return 0;
}
结果如下:

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐