C++(11):包含和继承关系

一、包含关系
当一个类构建的对象为另一个类的成员对象时:
当一个类型包含另一个对象时,本类没有构造,析构,拷贝,赋值,但成员类有这些函数,本类就可以进行自己的合成因此来调动成员对象的函数。要和成员对象的行为保持一致。

class Object
{
	int value;
public:
	Object(int x = 0) :value(x)
	{ 
		cout << "构建" << this << endl; 
	}
	~Object()
	{
		cout << "析构" << this << endl;
	}
	Object(const Object& obj) :value(obj.value)
	{
		cout << "Object::拷贝" << this << endl;
	}
	Object& operator=(const Object& obj)
	{
		if (this != &obj)
		{
			value = obj.value;
		}
		cout << "Object::赋值" << this << endl;
		return *this;
	}
};

class Base
{
	int num;
	Object obj;
public:
	Base(int x = 0) :num(x),obj(x) //若是没有会进行合成,以下同理
	{
		cout << "构建" << this << endl;
	}
	~Base()
	{
		cout << "析构" << this << endl;
	}
	Base(const Base& base) :num(base.num),obj(base.obj)
	{
		cout << "Object::拷贝" << this << endl;
	}
	Base& operator=(const Base& base)
	{
		if (this != &base)
		{
			num = base.num;
			obj = base.obj;
		}
		cout << "Base::赋值" << this << endl;
		return *this;
	}
};

int main()
{
	Base base1(10);
	Base base2(base1);
	Base base3;
	base3 = base1;
	return 0;
}

二、继承关系
当一个类继承另一个类时:
拷贝构造:
①无论基类写或不写拷贝或赋值函数,子类没写时都会进行合成,(注意若子类写了拷贝函数,在调用基类的拷贝构造,要写明(Object(base)))
②基类没有拷贝函数,子类有拷贝函数。不可以让父进行合成,只能调动构造函数来创建base2的隐藏父对象。
即:对于拷贝构造函数来说,基类可以约束子类进行合成,反过来,子类不能约束基类进行合成
赋值函数
①基类没有,子类也没有:正常赋值,将base1的值全部给base3。
②基类没有,子类有:只能赋值子对象的成员属性。
③基类有,子类没有:会约束子类产生赋值语句,正常赋值,基类和父类对象的属性都会赋值。
④基类有,子类也有:子类的赋值语句无法调动父类的赋值语句,只能赋值子对象的成员属性。

class Object
{
	int value;
public:
	Object(int x = 0) :value(x)
	{ 
		cout << "构建" << this << endl; 
	}
	~Object()
	{
		cout << "析构" << this << endl;
	}
	Object(const Object& obj) :value(obj.value)
	{
		cout << "Object::拷贝" << this << endl;
	}
	Object& operator=(const Object& obj)
	{
		if (this != &obj)
		{
			value = obj.value;
		}
		cout << "Object::赋值" << this << endl;
		return *this;
	}
};

class Base:public Object
{
	int num;
public:
	Base(int x = 0) :num(x),Object(x)
	{
		cout << "构建" << this << endl;
	}
	~Base()
	{
		cout << "析构" << this << endl;
	}
	Base(const Base& base) :num(base.num),Object(base)
	{
		cout << "Object::拷贝" << this << endl;
	}
	Base& operator=(const Base& base)
	{
		if (this != &base)
		{
			num = base.num;
		}
		cout << "Base::赋值" << this << endl;
		return *this;
	}
};

int main()
{
	Base base1(10);
	Base base2(base1);
	Base base3;
	base3 = base1;
	return 0;
}
  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值