简体   繁体   English

C ++覆盖功能

[英]C++ overriding function

I have tried to solve this problem for several days now without any luck. 我已经尝试解决这个问题好几天了,没有任何运气。

Im trying to override a function. 我试图覆盖一个功能。 This is the header for the parent class: 这是父类的标题:

class DComponent{
public:
virtual void mouseDown(int button, int x,int y){}
};

Header for the child class: 子类的标题:

class DButton:public DComponent{
public:
void mouseDown(int button,int x, int y);
};

And the cpp for the child: 和孩子的cpp:

#include "DButton.h"
void DComponent::mouseDown(int button, int x,int y){
}

And i get this error: 我得到这个错误:

    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'

I have also tried to not define the virtual function, but then i get link errors. 我也尝试过不定义虚函数,但随后出现链接错误。

Any help is greatly appreciated! 任何帮助是极大的赞赏!

In the header file you define the method, then you re-define it in the source file. 在头文件中定义方法,然后在源文件中重新定义它。

You should define it for the DButton class instead: 您应该改为为DButton类定义它:

void DButton::mouseDown(int button, int x,int y){
}

Also, I recommend you make the DComponent method a pure virtual method, by using 另外,我建议您通过使用以下方法使DComponent方法成为纯虚拟方法:

virtual void mouseDown(int button, int x,int y) = 0;
#include <iostream>

class DComponent{
public:
virtual void mouseDown(int button, int x,int y){
    std::cout << "Parent\n";
}
};


class DButton:public DComponent{
public:
void mouseDown(int button,int x, int y){
    std::cout << "Child\n";
}
};

int main(){
    DComponent parent;
    DButton child;

    parent.mouseDown(0,0,0);
    child.mouseDown(0,0,0);
    return 0;
}

Will print 将打印

Parent Child 亲子

If you don't want to specify a function for the parent class remember to make it pure virtual 如果您不想为父类指定函数,请记住将其设为纯虚拟

virtual void mouseDown(int button, int x,int y) = 0;

If you want to override also DButton method make it virtual. 如果您还想覆盖DButton方法,请使其为虚拟方法。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM