Inheritance of virtual member functions with the same name

我只是一个虾纸丫 提交于 2019-12-22 17:42:47

问题


class A
{
A() {};
virtual ~A() {};
virtual void Start() {};
virtual void Start(float a) {};
};

class B : public A
{ };

class C : public A
{
virtual void Start(float a) {};
}


...
B BObj;
BObj.Start(); // -> fine, no complain from g++
...

...
C CObj;
CObj.Start(); // -> not fine -> error: no matching function for call to ‘C::Start()’
...

I suspect that the problem comes from that both virtual functions have the same name, but different parameter signature. What I would like to know is that this is a g++-specific error message, how it is implemented the vtable, or it is an error based on the C++ standard.


回答1:


Overloading function hides all other Start functions. To use them add using A::Start:

class C : public A
{
public:
using A::Start;
virtual void Start(float a) {};
}

Also make Start public in A too.

Edit: Here you can find why derived class hides base class functions.




回答2:


The overload for Start in C hides all of the overloaded Start versions from A. If you did not try to overload Start in A [i.e. Start0(), Start1(float)] you wouldnt see this problem.




回答3:


You seek to call Start() on a CObj. But there is no such function because the only function defined is the overloaded Start(float a) which takes in a float parameter.

Exactly as the compiler says.

If a Start() function is deflared in the C class, calling this function should be fine. It can be declared as virtual and ned not be defined/implemented.

Hope this helps.




回答4:


class A
{
public:
    A() {}
    virtual ~A() {}

    virtual void Start() {}
    virtual void Start(float a) {}
};

class B : public A
{
};

class C : public A
{
public:
    using A::Start;
    virtual void Start(float a) {}
};

int main ()
{
    B BObj;
    BObj.Start();

    C CObj;
    CObj.Start ();
}



回答5:


when you overload a function in another class, for ever call overloaded function if else you call it. for example

class A()
{
    void start();

};
class B:public A
{
   void start();
   void Start();{A::start}//this function call it's father function
}
void main()
{
  A a;
  B b;
  a.start();//call own function,start() in A.
  b.start();//call is own function,start() in B.
  b.Start();//call start() in A.
}


来源:https://stackoverflow.com/questions/4891139/inheritance-of-virtual-member-functions-with-the-same-name

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!