码迷,mamicode.com
首页 > 编程语言 > 详细

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

时间:2014-08-14 14:19:28      阅读:188      评论:0      收藏:0      [点我收藏+]

标签: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;
}




bubuko.com,布布扣

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

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

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

obj1=obj;

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

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


C++赋值函数与拷贝构造函数应注意的问题,布布扣,bubuko.com

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

标签:c++赋值函数与拷贝构造函数应注意的问题

原文地址:http://blog.csdn.net/cjc211322/article/details/38555041

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!