C++继承细节 -2
继承与动态内存分配
//基类定义 class BaseClass { private: char *label; public: BaseClass() {} BaseClass(const char *l); virtual ~BaseClass(); BaseClass(const BaseClass &bc); BaseClass &operator=(const BaseClass &bc); }; BaseClass::BaseClass(const BaseClass &bc) { this->label = new char[std::strlen(bc.label)+1]; std::strcpy(this->label, bc.label); } BaseClass &BaseClass::operator=(const BaseClass &bc) { this->label = new char[std::strlen(bc.label)+1]; std::strcpy(this->label, bc.label); } BaseClass::~BaseClass() { delete[] this->label; }
派生类中的数据成员没用
new
分配内存,则不需要为派生类提供 复制构造函数、赋值运算符;因为在使用已知对象对另一个对象初始化时派生类的默认复制函数将调用基类的显示复制函数(BaseClass(const BaseClass &bc))进行深拷贝,同理赋值运算符也一样。//派生类定义 class DerivedClass : public BaseClass { private: char style[]; //使用栈空间 public: DerivedClass() {} DerivedClass(const char *st); };
派生类中的数据成员使用
new
分配内存,则派生类需要提供 复制构造函数、 赋值运算符,具体实现如下://派生类 class DerivedClass : public BaseClass { private: char *style; public: DerivedClass() {} DerivedClass(const char *st); ~DerivedClass() {delete[] this->style;} DerivedClass(const DerivedClass &dc); DerivedClass &operator=(const DerivedClas &dc); }; //显示复制构造函数 DerivedClass::DerivedClass(const DerivedClass &dc) : BaseClass(dc) { this->style = new char[std::strlen(dc.style)+1]; std::strcpy(this->style, dc.style); } //赋值运算符 DerivedClass & DerivedClass::operator=(const DerivedClass &dc) { if (this == &dc) { return *this; } delete[] this->style; //注意,注意,注意 BaseClass::operator=(dc); //显示调用基类赋值运算符函数 this->style = new char[std::strlen(dc.style)+1]; std::strcpy(this->style, dc.style); return *this; }
相关推荐
zuihaobushi 2020-04-30
xasdfg 2020-04-25
xiaohouye 2020-04-20
yuuuuy 2020-01-19
lynjay 2020-06-14
88384957 2020-06-12
菇星獨行 2020-04-20
qscool 2020-04-16
Joymine 2020-03-04
CosEmon 2020-03-01
GoatSucker 2020-02-15
Joymine 2020-02-11
twater000 2020-02-01
ILVNMM 2020-10-26
PinkBean 2020-08-19
Seandba 2020-08-16
徐建岗网络管理 2020-07-28
AaronPlay 2020-06-13
herohope 2020-06-10