我已经尝试解决这个问题好几天了,但没有任何运气。
我试图覆盖一个函数。这是父类的标题:
class DComponent{
public:
virtual void mouseDown(int button, int x,int y){}
};
子类的标题:
class DButton:public DComponent{
public:
void mouseDown(int button,int x, int y);
};
还有 child 的cpp:
#include "DButton.h"
void DComponent::mouseDown(int button, int x,int y){
}
我得到这个错误:
1>c:\users\daffern\documents\visual studio 2012\projects\spel\spel\dbutton.cpp(26): error C2084: function 'void DComponent::mouseDown(int,int,int)' already has a body
1> c:\users\daffern\documents\visual studio 2012\projects\spel\spel\dcomponent.h(13) : see previous definition of 'mouseDown'
我也尝试过不定义虚函数,但随后出现链接错误。
非常感谢任何帮助!
最佳答案
在头文件中您定义方法,然后在源文件中重新定义它。
您应该为 DButton
类定义它:
void DButton::mouseDown(int button, int x,int y){
}
此外,我建议您通过使用使 DComponent 方法成为纯虚方法
virtual void mouseDown(int button, int x,int y) = 0;
关于C++ 覆盖函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17013654/