【发布时间】:2014-07-07 09:44:57
【问题描述】:
我希望这会起作用:
template <typename T> class MyBaseClass
{
public:
MyBaseClass();
virtual ~MyBaseClass();
void DoSomething(const T& myClass);
// Implemented in .cpp file
virtual void DoSomething(int n, const T& myClass);
// Implemented in .cpp file
};
class MyDerivedClass : public MyBaseClass<int>
{
public:
virtual void DoSomething(int n, const int& myInt);
// Implemented in .cpp file
};
...在我的代码中的其他地方:
int i;
MyDerivedClass myClass;
myClass.DoSomething(i);
但是,它没有;相反,它无法编译并显示错误提示(在 Visual C++ 的情况下)
error C2660: 'int::DoSomething' : function does not take 1 arguments
...即使明显是一个DoSomething的版本,在基类中声明,确实只接受一个参数。如果我用派生类中的 两个 参数注释掉 DoSomething 的重新定义,错误就会消失。
我违反了哪些微妙的 C++ 规则,有没有一种优雅的方法可以解决这个问题?
【问题讨论】:
-
抱歉,我的第一条评论有误。
-
请编辑您的代码,
myBaseClass需要大写首字母,int MyDerivedClass需要是class MyDerivedClass -
我猜这是函数查找的一些复杂性。该函数在派生中找到,不再进一步查看;只有在重载解析(在派生内)尝试失败(派生不声明该签名)。参照。 en.cppreference.com/w/cpp/language/overload_resolution
-
顺便说一句,
template <typename T> void MyBaseClass<T>::DoSomething(const T& myClass)的实现应该放在标题中... -
@TemplateRex,你说得对;我已经这样做了。
标签: c++ inheritance overloading virtual