相关疑难解决方法(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万
查看次数

在派生类中具有相同名称但签名不同的函数

我有一个具有相同名称的函数,但在基类和派生类中具有不同的签名.当我尝试在继承自派生的另一个类中使用基类的函数时,我收到一个错误.请参阅以下代码:

class A
{
    public:
    void foo(string s){};
};

class B : public A
{
    public:
    int foo(int i){};
};

class C : public B
{
    public:
    void bar()
    {
        string s;
        foo(s);
    }
};
Run Code Online (Sandbox Code Playgroud)

我从gcc编译器收到以下错误:

In member function `void C::bar()': no matching function for call to `C::foo(std::string&)' candidates are: int B::foo(int)
Run Code Online (Sandbox Code Playgroud)

如果我int foo(int i){};从课堂上删除B,或者我将其重命名foo1,一切正常.

这有什么问题?

c++ lookup inheritance function c++-faq

83
推荐指数
2
解决办法
4万
查看次数

标签 统计

c++ ×2

c++-faq ×1

function ×1

inheritance ×1

lookup ×1

overriding ×1

polymorphism ×1