接口继承
Inheritance with interfaces
我目前正在努力了解 C++ 继承的基础知识。考虑以下代码:
// Interfaces
class InterfaceBase
{
public:
virtual void SomeMethod() = 0;
};
class InterfaceInherited : public InterfaceBase
{
};
// Classes
class ClassBase : public InterfaceBase
{
public:
virtual void SomeMethod()
{
}
};
class ClassInherited : public ClassBase, public InterfaceInherited
{
};
int main()
{
ClassBase myBase; // OK
ClassInherited myInherited; // Error on this line
return 0;
}
这里我有两个具有继承关系的接口。实现接口的两个 classes 也是如此。
这给了我以下编译器错误:
C2259 'ClassInherited': cannot instantiate abstract class
似乎 class ClassInherited 没有从 ClassBase[ 继承 SomeMethod 的实现=27=]。因此它是抽象的,不能被实例化。
为了让 ClassInherited 从 ClassBase 继承所有已实现的方法,我需要如何修改这个简单的示例?
您遇到了 diamond problem。
解决方案是使用virtual inheritance (Live),确保只有一份基class成员被孙子继承:
// Interfaces
class InterfaceBase
{
public:
virtual void SomeMethod() = 0;
};
class InterfaceInherited : virtual public InterfaceBase
{
};
// Classes
class ClassBase : virtual public InterfaceBase
{
public:
virtual void SomeMethod()
{
}
};
class ClassInherited : public ClassBase, public InterfaceInherited
{
};
int main()
{
ClassBase myBase; // OK
ClassInherited myInherited; // OK
return 0;
}
我目前正在努力了解 C++ 继承的基础知识。考虑以下代码:
// Interfaces
class InterfaceBase
{
public:
virtual void SomeMethod() = 0;
};
class InterfaceInherited : public InterfaceBase
{
};
// Classes
class ClassBase : public InterfaceBase
{
public:
virtual void SomeMethod()
{
}
};
class ClassInherited : public ClassBase, public InterfaceInherited
{
};
int main()
{
ClassBase myBase; // OK
ClassInherited myInherited; // Error on this line
return 0;
}
这里我有两个具有继承关系的接口。实现接口的两个 classes 也是如此。
这给了我以下编译器错误:
C2259 'ClassInherited': cannot instantiate abstract class
似乎 class ClassInherited 没有从 ClassBase[ 继承 SomeMethod 的实现=27=]。因此它是抽象的,不能被实例化。
为了让 ClassInherited 从 ClassBase 继承所有已实现的方法,我需要如何修改这个简单的示例?
您遇到了 diamond problem。 解决方案是使用virtual inheritance (Live),确保只有一份基class成员被孙子继承:
// Interfaces
class InterfaceBase
{
public:
virtual void SomeMethod() = 0;
};
class InterfaceInherited : virtual public InterfaceBase
{
};
// Classes
class ClassBase : virtual public InterfaceBase
{
public:
virtual void SomeMethod()
{
}
};
class ClassInherited : public ClassBase, public InterfaceInherited
{
};
int main()
{
ClassBase myBase; // OK
ClassInherited myInherited; // OK
return 0;
}