我有一个名为Packet
的基类:
// Header File
class Packet {
public:
virtual bool isAwesome() const {
return false;
}
}
和一个名为AwesomePacket
的继承类:
// Header File
class AwesomePacket : public Packet {
public:
virtual bool isAwesome() const {
return true;
}
}
但是,当我实例化AwesomePacket
并调用isAwesome()
时,该方法会返回false
而不是true
。为什么会这样?
答案 0 :(得分:8)
您的代码调用在Packet构造函数中是非常有用的:
Packet::Packet()
{
// this will always call Packet::isAwesome
if (isAwesome())
{
}
}
即使使用此Packet构造函数构造AwesomePacket对象的父对象,也不会调用AwesomePacket :: isAwesome。这是因为此时对象还不是AwesomePacket。
答案 1 :(得分:4)
这完全取决于你如何调用该方法。考虑一下:
AwesomePacket ap;
bool awesomeness0( ap.isAwesome()); // true, call is direct, not through vtable
AwesomePacket& rap( ap );
bool awesomeness1( rap.isAwesome()); // true, call is direct, not through vtable
Packet p( ap ); // WRONG (but legal): slicing child instance into space of parent
bool awesomeness2( p.isAwesome()); // false, call is direct, not through vtable
const Packet& rp( ap ); // the right way
bool awesomeness3( rp.isAwesome()); // true, call is through vtable
const Packet* pp( &ap ); // also the right way
bool awesomeness4( pp->isAwesome()); // true, call is through vtable
这就是说C ++中的多态性只能通过引用或指向base的指针来工作。