向上类型转换和拷贝构造函数

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

 

转载于:https://www.cnblogs.com/phoenixzq/archive/2010/11/17/1880128.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值