<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;
所谓初始化,即声明(分配存储空间),使用有操作数进行初始化。
C++赋值函数与拷贝构造函数应注意的问题
时间: 2024-10-10 01:34:41