如何删除继承的私有char*属性?(例如:在析构函数中)

Max*_* M. 1 c++ inheritance attributes char

我试图删除char*此程序中的继承属性:

在啊

class A {    
  public :
    // Functions, constructors and such
  private :
    char* attribute;
}
Run Code Online (Sandbox Code Playgroud)

在Bh

#include "A.h"

class B : public A {
  public :
    B(const char* _attribute, int s) : A(_attribute) {setSpeed(s);}
    ~B()
  private :
    int speed;
}
Run Code Online (Sandbox Code Playgroud)

在析构函数中使用delete [],如下所示:

B::~B() {
  delete [] attribute;
}
Run Code Online (Sandbox Code Playgroud)

但我得到这个错误:`char*A :: attribute'是私有的

在A的destuctor(~A())中,我使用相同的"destroy []属性",它有效......

Kar*_*k T 6

由于它是A的私有,因此A应该是负责删除它的类.

你不应该在B中删除它,这违反了基本的封装.B应该只关注删除自己的属性.

  • @ user1944839,在`B`之后将自动调用`A`的析构函数.无论如何,考虑使用`std :: string`而不是`char*`.然后,没有人必须清理它. (2认同)