如何访问继承的成员

how to access inherited member

本文关键字:继承 成员 访问 何访问      更新时间:2023-10-16

我有一个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