/*向上类型转换和拷贝构造函数拷贝构造函数拷贝构造函数
如果允许便以其为派生类生成拷贝构造函数
,它将首先自动调用基类的拷贝构造函数
,然后再是各成员对象的拷贝构造函数
*/
#include <iostream>
using namespace std;
class Parent{
int i;
public:
Parent(int ii):i(ii){
cout << "Parent(int ii)
";
}
Parent(const Parent& b):i(b.i){
cout << "Parent(const Parent&)
";
}
Parent():i(0){cout << "Parent()
";}
friend ostream& operator<<(ostream& os,const Parent& b){
return os << "Parent: " << b.i << endl;
}
};
class Member{
int i;
public:
Member(int ii):i(ii){
cout << "Member(int ii)
";
}
Member(const Member& m):i(m.i){
cout << "Member(const Member&)
";
}
friend ostream& operator<<(ostream& os,const Member& m){
return os << "Member: " << m.i << endl;
}
};
class Child:public Parent{
int i;
Member m;
public:
Child(int ii):Parent(ii),i(ii),m(ii){
cout << "Child(int ii)
";
}
Child(const Child& c):Parent(c),i(c.i),m(c.m){//无论何时我们在创建自己的拷贝构造函数时,都要正确地调用基类拷贝构造函数
cout << "Child(Child&)
";
}
friend ostream& operator<<(ostream& os,const Child& c){
return os << (Parent&)c << c.m
<< "Child: " << c.i << endl;
}
};
int main(){
Child c(2);
cout << "calling copy-constructor: " << endl;
Child c2 = c;
cout << "Values in c2:
" << c2;
return 0;
}