继承与动态内存分配
//基类定义 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[20]; //使用栈空间 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; }
C++继承细节 -2
猜你喜欢
转载自www.cnblogs.com/Focus-Flying/p/9101508.html
今日推荐
周排行