无法从子实例调用基类的公共方法

Unable to call public method of the base class from a child's instance

本文关键字:方法 基类 调用 实例      更新时间:2023-10-16

我想在C++中尝试构造函数继承,结果很好。但后来我发现,我真的不能从Daughter的实例中调用方法。Visual studio表示

方法Mother::ShowName不可用

即使它是公开的,就我而言,这必须从儿童班获得。我做错什么了吗?

class Mother{
protected:
  char* name;
public :    
  Mother(char* _name){
      name = _name;
  }
  void ShowName(){
      cout << "my name is: " << name << endl;
  }
};

class Daughter : Mother{
public:
  Daughter(char* _name) : Mother(_name) {
  }
};
int main(){
  Daughter d1("Masha");
  d1.ShowName();
  return 0;
}

class Daughter : Motherprivate继承。默认情况下,class继承与此类似。

class Daughter : public Mother就是您想要的。

您需要使用public继承:

class Daughter : public Mother

您需要使用访问说明符public继承母类。默认情况下,c++将其视为私有。

正如Grigore所指出的,您应该显式添加"public"。

F。Y.I,C++标准如下:

在没有基类的访问说明符的情况下,当用类键结构定义派生类时,假定为public,而当用类密钥类定义类时,则假定为private。