如何访问继承的成员
how to access inherited member
我有一个A类和一个B类,如下所示:
class A
{
public:
A(){}
};
class B : public A
{
public:
B() : A()
{
value = 10;
}
int Value()
{
return value;
}
protected:
int value;
}:
我有这个代码:
int main()
{
A* a = new B();
// how can I access to Value() ? I would like to make that :
int val = a->Value();
// must i cast a to B ? how ?
}
感谢您的帮助。
使 Value() 成为 A 中的纯虚函数(同时添加一个虚拟析构函数):
class A
{
public:
A(){}
virtual ~A(){}
virtual int Value() = 0;
};
问题是,Virtual() 不是继承的。它未在 A 中定义。
在 A 中将 Value() 声明为纯虚拟。
virtual int Value() = 0;
您无法访问 Value(),因为就编译器而言,A 中没有 Value() 函数(这是您正在创建的对象类型)。
使用虚拟方法
class A
{
public:
A(){}
virtual int Value() = 0;
virtual ~A(){}
};
class B : public A
{
public:
B() : A()
{
value = 10;
}
int Value()
{
return value;
}
protected:
int value;
}:
还要记住(告诉不要问原则)。
改为执行以下操作:
B* b = new B();
如果您需要B
的功能,请制作B
。
相关文章:
- 为什么我可以通过SubBase类的公共继承方法打印出基类的私人继承成员
- 派生类调用使用非继承成员的继承函数
- 如果存在具有不同参数的继承成员,为什么对 C++ 结构函数的调用不明确?
- C :原始成员与继承成员的优先级
- 更改继承成员的地址
- C 是否可以不继承成员
- 使用模板的继承阴影继承成员
- 继承成员功能的模板专业化
- 不允许继承成员,为什么
- 派生模板类和继承成员变量的语法谜题
- 继承成员地址的C++标准
- 多级继承成员访问
- 访问专用模板的私有/继承成员变量
- 基模板继承成员,减少所需的类型
- 继承成员函数指针
- 模板专用化类不继承成员
- C++14正在初始化类构造函数初始化列表中的继承成员
- 具有专门初始化的继承成员变量
- 模板继承成员字段
- 访问数据成员的继承成员函数