为什么类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;
答案 0 :(得分:6)
问题是TB
从IA
继承两次,因为IA
是IB
和TA
的父级。要解决此问题,您需要重新设计类层次结构或使用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;
}