#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:复制对象时勿忘其每一个成分
最新推荐文章于 2025-07-30 22:59:24 发布
本文详细介绍了C++中类的拷贝构造函数和拷贝赋值运算符的实现过程,通过示例展示了如何正确地重载这两个运算符以避免深拷贝带来的性能问题。
1272

被折叠的 条评论
为什么被折叠?



