简体   繁体   中英

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:

#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:

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

Also, I recommend you make the DComponent method a pure virtual method, by using

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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