无法从子实例调用基类的公共方法
Unable to call public method of the base class from a child's instance
我想在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 : Mother
是private
继承。默认情况下,class
继承与此类似。
class Daughter : public Mother
就是您想要的。
您需要使用public
继承:
class Daughter : public Mother
您需要使用访问说明符public继承母类。默认情况下,c++将其视为私有。
正如Grigore所指出的,您应该显式添加"public"。
F。Y.I,C++标准如下:
在没有基类的访问说明符的情况下,当用类键结构定义派生类时,假定为public,而当用类密钥类定义类时,则假定为private。
相关文章:
- 在模板基类中为继承类中的可选重写生成虚拟方法
- 为什么此派生对象无法访问基类的后递减方法?
- 使用基类中的派生方法运行线程,而无需使用模板
- 将子类方法声明为基类的友元
- 是否可以使用基类非虚拟方法中的派生类虚拟方法?
- 在派生类中使用基类的私有成员变量的最佳方法
- 如何在成为指向基类的指针后保留对子类方法的使用?
- 从基类实例调用派生类方法而不进行强制转换
- 继承:调用基类的成员和方法
- 通过基类接受方法转发派生 UniquePtr 的右值会移动引用而不是复制
- 引用基类模板的成员变量的简单方法
- C++ 使用派生类方法更改基类数据成员
- C++初始化之前派生类调用基类的方法
- 将派生类方法与基类unique_ptr一起使用
- 为什么派生类的实例从基类调用方法?
- 基类可以声明虚拟方法但不定义它吗?仍然在派生类中定义
- googletest:测试基类具有纯虚拟方法的派生类时的核心转储
- 从基类调用重写的方法
- 为什么允许将派生类的方法static_cast为基类的方法?
- C++-从方法基类调用派生类中的重写方法