C++ 覆盖函数

标签 c++ function polymorphism virtual

我已经尝试解决这个问题好几天了,但没有任何运气。

我试图覆盖一个函数。这是父类的标题:

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/

相关文章:

c++ - 带有映射迭代器的错误访问内存

python - TypeError:强制转换为 Unicode,需要字符串或缓冲区,找不到 NoneType

java - 使用 Java 参数化类型和多态性实现这种通用编程场景的方法

c++ - 没有指针的多态性

php - 从公共(public)基函数访问类层次结构中的私有(private)属性

C++线程应用程序运行速度比非线程慢

c# - 将 C++ 例程转换为 C#,主要是指针

java - 将 Web 技术用于 UI

ios - Swift 中的惰性函数

mysql - 将查询结果插入到 MySQL 表中的一个字段中,并将 SQL 函数返回的值插入到其他字段中