我最近被问到一个基本的 C++ 问题,我实际上并不知道答案,而且我从未发现答案是什么。这是问题:
运行此程序时,可能会导致错误。您会对 Base 类进行哪些更改来修复它?
#include <iostream>
class Base {
public:
virtual void ShowMessage () {
std::cout << "Base class message\n";
}
// Something should be added here!
};
class Derived : public Base {
public:
explicit Derived (const std::string & value)
: myValue(value)
{
}
virtual void ShowMessage () {
std::cout << "Derived class message " << myValue << "\n";
}
private:
std::string myValue;
};
int main () {
Base * obj = new Derived("Test message");
obj->ShowMessage();
delete obj;
}
它在我的机器上编译并运行得很好。有人知道他们在找什么吗?