相关疑难解决方法(0)

为什么派生类中的重写函数会隐藏基类的其他重载?

考虑一下代码:

#include <stdio.h>

class Base {
public: 
    virtual void gogo(int a){
        printf(" Base :: gogo (int) \n");
    };

    virtual void gogo(int* a){
        printf(" Base :: gogo (int*) \n");
    };
};

class Derived : public Base{
public:
    virtual void gogo(int* a){
        printf(" Derived :: gogo (int*) \n");
    };
};

int main(){
    Derived obj;
    obj.gogo(7);
}
Run Code Online (Sandbox Code Playgroud)

得到此错误:

>g++ -pedantic -Os test.cpp -o test
test.cpp: In function `int main()':
test.cpp:31: error: no matching function for call to `Derived::gogo(int)'
test.cpp:21: note: candidates are: virtual …

c++ polymorphism overriding

212
推荐指数
3
解决办法
5万
查看次数

C++重载决议

鉴于以下示例,为什么我必须明确使用该语句b->A::DoSomething()而不仅仅是b->DoSomething()

编译器的重载决议不应该弄清楚我在谈论哪种方法?

我正在使用Microsoft VS 2005.(注意:在这种情况下使用虚拟无效.)

class A
{
  public:
    int DoSomething() {return 0;};
};

class B : public A
{
  public:
    int DoSomething(int x) {return 1;};
};

int main()
{
  B* b = new B();
  b->A::DoSomething();    //Why this?
  //b->DoSomething();    //Why not this? (Gives compiler error.)
  delete b;
  return 0;
}
Run Code Online (Sandbox Code Playgroud)

c++ overloading resolution function

36
推荐指数
4
解决办法
1万
查看次数