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

How to delete an inherited private char* attribute? (example : in a destructor)

本文关键字:属性 例如 析构函数 删除 何删除 继承 char      更新时间:2023-10-16

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

在A.h

class A {    
  public :
    // Functions, constructors and such
  private :
    char* attribute;
}
在B.h

#include "A.h"
class B : public A {
  public :
    B(const char* _attribute, int s) : A(_attribute) {setSpeed(s);}
    ~B()
  private :
    int speed;
}

在析构函数中使用delete []:

B::~B() {
  delete [] attribute;
}

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

在A的析构函数(~A())中,我使用相同的"destroy[]属性",它可以工作…

因为它是A私有的,所以A应该是负责删除它的类。

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

你在类A中的属性被定义为private,所以它不被类b继承。它不存在于类b中,这就是为什么你不能删除它。

尝试使用protected.

不能从派生类访问基类的私有变量。如果您希望从派生类访问它,则需要使其受保护。