0

以下代码:

class Base1
{
public:
    void go() {}
};

class Base2
{
public:
    void go(int a) {}
};

class Derived : public Base1, public Base2 {};

int main()
{
    Derived d;

    d.go(3);

    return 0;
}

编译时会报错:

g++ -o a a.cc
a.cc: In function ‘int main()’:
a.cc:19:7: error: request for member ‘go’ is ambiguous
a.cc:10:10: error: candidates are: void Base2::go(int)
a.cc:4:10: error:                 void Base1::go()
make: *** [a] Error 1

很容易看出基类中的原型是不同的。但是为什么编译器不能检测到这一点并自动选择匹配的呢?

4

1 回答 1

4

不允许跨类边界重载函数。您可以通过像这样编写 Derived 类来解决此问题 -

class Derived : public Base1, public Base2
{
public:
    using Base1::go;
    using Base2::go;
};
于 2012-06-08T06:32:18.983 回答