#include<iostream>
#include<string>
using namespace std;
void logCall(const string&funcName){};
class Date{};
class Base{
public:
//....
Base(){}
Base(const Base&rhs){
logCall("A::copy constructor");
}
Base&operator=(const Base&rhs){
logCall("A::copy assignment operator");
name = rhs.name;
return *this;
}
private:
string name;
Date d;
};
class Derived :public Base{
public:
//..
Derived(){}
Derived(const Derived&rhs):Base(rhs)/*这里如果不写会调用默认,但会报错*/,m_i(rhs.m_i){
logCall("Derived::copy constructor");
}
/*Derived&operator=(const Derived&rhs){
logCall("Derived::copy assignment operator");
Base::operator=(rhs);//这里也要对基类部分进行拷贝赋值 因为无法访问基类的私有成员变量
m_i = rhs.m_i;
return *this;
}*/
Derived &operator=(const Derived &rhs){
logCall("Derived::copy assignment operator");
if (this != &rhs){
static_cast<Base&>(*this) = rhs;
}
return *this;
}
private:
int m_i;
};
条款12:复制对象时勿忘其每一个成分
最新推荐文章于 2023-07-15 16:37:05 发布