鉴于上面的描述,您应该无法实例化 的实例,CPet
因为纯虚函数IAnimal::isAlive()
在IPet
vtable 中未定义。
struct IAnimal {
virtual ~IAnimal() {}
virtual void isAlive() = 0;
};
struct IPet : public IAnimal {
};
struct CAnimal : public IAnimal {
virtual void isAlive() {
}
};
struct CPet : public CAnimal, public IPet {
};
int main(void) {
CPet cp;
}
使用 Visual C++ 2008 和 2010 编译时产生以下内容:
animal.cpp(18) : error C2259: 'CPet' : cannot instantiate abstract class
due to following members:
'void IAnimal::isAlive(void)' : is abstract
mytest.cpp(5) : see declaration of 'IAnimal::isAlive'
GCC 会产生类似的警告:
animal.cpp: In function 'int main()':
animal.cpp:18:7: error: cannot declare variable 'cp' to be of abstract type 'CPet'
animal.cpp:14:8: note: because the following virtual functions are pure within 'CPet':
animal.cpp:3:15: note: virtual void IAnimal::isAlive()