的基類確實實現的功能,它只是實現它錯了。它與vtables或任何複雜的東西無關。解決方案4首選(因爲它可以防止構建錯誤的程序),如果不可能/需要1或2的順序。
請注意,錯誤與虛擬功能或一般繼承無關(您不使用Bar
,您有沒有注意到?)。它甚至與班級沒有關係,但也可能發生在任何獨立功能上。考慮:
#include <iostream>
#include <string>
// Note: UB -- nothing returned
int getInt() {}
std::string getStr() {}
int main(int argc, char ** argv)
{
// This probably works (read access from an arbitrary
// location on the stack which is in the prog's address space)
std::cout << getInt() << std::endl;
// This will crash. operator<< will try to access memory through
// a pointer value which is some arbitrary byte pattern on the stack.
// Probably not in the prog's address space.
// Then the destructor for the temporary string will
// try to delete the same
// memory which will crash in any case, even if it happens to
// point to valid memory (which, alas, was never allocated).
std::cout << getStr();
std::cout << "Still alive?\n"; // never printed
std::cout.flush();
return 0;
}
爲了防止您的原始代碼發生錯誤,只需返回一個值即可。如果實現的功能,不要扔或中止(這是三種選擇),即如果您返回時,你必須返回值:
#include <iostream>
class Foo
{
public:
virtual std::string myString() { return "test\n";}
};
class Bar : public Foo
{
public:
};
int main(int argc, char ** argv)
{
Foo * bar = new Foo();
std::cout << bar->myString();
return 0;
}
這個例子不會崩潰,是嗎?顯示一個。編輯:哦,我的,它的確如此。我很困惑。 –
你是什麼意思的「最佳解決方案」? –
@PeterSchneider - 至少在這裏。 –