派生类仍然是抽象的

时间:2018-02-21 11:26:42

标签: c++

为什么类TB在以下代码中是抽象的?

#include <stdio.h>

struct IA
{
    virtual long X() = 0;
};
struct IB: public IA
{
    virtual long Y() = 0;
};

struct TA: public IA
{
    virtual long X() { return 5; };
};

struct TB: public IB, public TA
{
   // virtual long X() { return TA:: X(); };
    virtual long Y() { return 7; };
};

int main()
{
    TB b;
}


main.cpp:25: error: cannot declare variable 'b' to be of abstract type 'TB'
     TB b;

1 个答案:

答案 0 :(得分:6)

问题是TBIA继承两次,因为IAIBTA的父级。要解决此问题,您需要重新设计类层次结构或使用virtual inheritance

#include <stdio.h>

struct IA
{
    virtual long X() = 0;
};
struct IB: public virtual IA // virtual inheritance here
{
    virtual long Y() = 0;
};

struct TA: public virtual IA // and here
{
    virtual long X() { return 5; };
};

struct TB: public IB, public TA
{
   // virtual long X() { return TA:: X(); };
    virtual long Y() { return 7; };
};

int main()
{
    TB b;
}