我有这个简单的代码:
class A {
public:
string toString() const { return "A"; }
};
class B : public A {
public:
string toString() const { // some code here }
};
我要toString()
在 B 类中将继承自 A 类并采用一些额外的值。在此示例中,将是:“AB”(A:来自类 A,B:额外字符串)。
这在 Java 中很容易,但我不知道在 C++ 中如何做。我的第一个想法是从 toString()
中获取字符串在 A 类中并附加附加字符串。所以,采取这个:我使用:static_cast<A>(const_cast(this))->toString()
但它不会工作:(
请帮帮我。谢谢:)
最佳答案
class A {
public:
string toString() const { return "A"; }
};
class B : public A {
public:
string toString() const { return A::toString() + "B"; }
};
在 MS 实现中(在 Windows 上),您可以改用 __super::toString() ,但这是一个不可移植的 MS 扩展。
关于C++:继承基类方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13501071/