PhoenixZq
分享是一门艺术~~

/*向上类型转换和拷贝构造函数拷贝构造函数拷贝构造函数
如果允许便以其为派生类生成拷贝构造函数,
它将首先自动调用基类的拷贝构造函数,
然后再是各成员对象的拷贝构造函数
*/
#include <iostream>
using namespace std;

 

class Parent{
int i;
public:
Parent(int ii):i(ii){
cout << "Parent(int ii)\n";
}
Parent(const Parent& b):i(b.i){
cout << "Parent(const Parent&)\n";
}
Parent():i(0){cout << "Parent()\n";}
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)\n";
}
Member(const Member& m):i(m.i){
cout << "Member(const Member&)\n";
}
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)\n";
}
Child(const Child& c):Parent(c),i(c.i),m(c.m){//无论何时我们在创建自己的拷贝构造函数时,都要正确地调用基类拷贝构造函数
cout << "Child(Child&)\n";
}
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:\n" << c2;
return 0;
}

 

posted on 2010-11-17 20:18  PhoenixZq  阅读(465)  评论(0编辑  收藏  举报