class Base
{
public:
string Test() { return "hi"; }
};
class Derived : public Base
{
public:
int Test() { return 3; }
}
我想要 Base 的“嗨”。怎么可能得到string s = Derived().Test()
上类?不,Test
没有参数。
我试过了 using Base::Derived
,但似乎仅返回类型不同的重载函数未被继承/公开。我无法引用 Base
来自客户端代码,因为 Base
将生成模板。客户知道它想要的类型。我无法获得 Test<string>()
也可以通过继承来工作。
最佳答案
那是因为你不是在重载,而是在隐藏。
你需要转换回基类。
Derived d;
d.Test(); //calls Derived::Test()
static_cast<Base>(d).Test(); //calls Base::Text()
不能根据返回类型重载函数:
1.3.11签名
the information about a function that participates in overload resolution (13.3): its parameter-type-list (8.3.5) and, if the function is a class member, the cv-qualifiers (if any) on the function itself and the class in which the member function is declared. [...]
关于c++ - 使用模板特化重载返回类型?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9368404/