C++赋值函数与拷贝构造函数应注意的问题

<pre name="code" class="cpp"><pre name="code" class="cpp">#include "stdafx.h"
#include <iostream>
using namespace  std;

class Base
{
public:
	Base(int i):num(i)
	{}
	Base(const Base& obj)
	{
		num=obj.num;
	}
	Base& operator=(const Base& obj);
public:
	int num;
};
Base& Base::operator=(const Base& obj)
{
	if(this!=&obj)
	{
		num=obj.num;
	}
	return *this;
}

class Derived:public Base
{
public:
	Derived(int i,int j):Base(i),num1(j)
	{}
	Derived(const Derived& obj):Base(obj)			//合法
	{
		//Base(obj);					//非法
		cout<<"Copy constructor"<<endl;
		num1=obj.num1;
	}
	Derived& operator=(const Derived& obj)
	{
		cout<<"Assign constructor"<<endl;
		if(this!=&obj)
		{
			Base::operator=(obj);
			num1=200;//obj.num1;
			return *this;
		}
	}
public:
	int num1;
};


int main()
{
	Derived obj(10,20);
	{
		Derived obj1(0,0);
		obj1=obj;
		cout<<obj1.num<<endl;
		cout<<obj1.num1<<endl;
	}
	{
		Derived obj1=obj;
		cout<<obj1.num<<endl;
		cout<<obj1.num1<<endl;
	}

	system("pause");
	return 0;
}


 
 

1、无论是在派生类的赋值函数还是拷贝构造函数中,都要显式调用基类的相应函数

2、派生类拷贝构造函数调用基类的拷贝构造函数时,只能在初始化列表中调用

3、下面的代码是赋值,调用赋值函数

obj1=obj;

下面的代码是初始化,调用的是拷贝构造函数。

Derived obj1=obj;
所谓初始化,即声明(分配存储空间),使用有操作数进行初始化。


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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值