c++ access derived class with a pointer from base class

时间:2017-12-24 16:24:50

标签: c++ pointers derived

The compiler keeps saying 'class A' has no member named 'foo'. I am trying to use a function from a derived class with a pointer. Here is my code:

 class A{
  .....
};

class B:public A{
     virtual void foo() = 0;
};

class C:public B{
....
public:
    void foo(){
        ....
    }
};

I have a table of A pointers named Table and when trying

Table[j]->foo()

I am getting the compiler error.

What should I do except cast?

2 个答案:

答案 0 :(得分:2)

您有编译错误,因为函数foo未在类A中声明。

您可以在A中将其声明为纯虚拟:

class A {
     virtual void foo() = 0;
};

在派生类中,您不必明确声明foo virtual。如果只有C是具体课程,则您根本不必在课程foo中声明B

如果您的示例如果您知道在指向A的指针数组中只有C类实例,则可以显式转换为C指针,但这是设计不佳的标志不推荐它:

static_cast<C*>(Table[j])->foo()

答案 1 :(得分:0)

如果你有一个指向基类的指针并且想要访问派生类型的成员你必须进行转换,那么你有一个指向派生类型的指针,无论是在你的情况下还是在你的情况下添加foo()虚拟成员到基地。

class A
{ ... };
class B : public A:{
{
public:
  virtual foo() { std::cout << "B::foo" << std::endl; }
};
class C : public B
{
public:
  void foo() { std::cout << "C::foo" << std::endl;
};
...
A * arr[8];
for(int i = 0; 8>i; ++i)
  arr[i] = new C;
((B*)arr[0])->foo(); // will print "C::foo\n"

但是,如果您将virtual void foo() = 0;添加到A,那么您可以arr[0]->foo(),它仍会打印C::foo