为什么具有相同名称但不同签名的多继承函数不会被视为重载函数? [英] Why do multiple-inherited functions with same name but different signatures not get treated as overloaded functions?

查看:180
本文介绍了为什么具有相同名称但不同签名的多继承函数不会被视为重载函数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

以下代码段在编译期间产生了一个对foo的歧义调用错误,我想知道是否有任何方式围绕这个问题,没有完全限定调用foo:

The following snippet produces an "ambigious call to foo" error during compilation, and I'd like to know if there is any way around this problem without fully qualifying the call to foo:

#include <iostream>

struct Base1{
    void foo(int){
    }
};

struct Base2{
    void foo(float){
    }
};

struct Derived : public Base1, public Base2{
};

int main(){
    Derived d;
    d.foo(5);

    std::cin.get();
    return 0;
}

所以,问题是标题说的。想法?我的意思是,以下工作完美无瑕:

So, question is as the title says. Ideas? I mean, the following works flawlessly:

#include <iostream>

struct Base{
    void foo(int){
    }
};

struct Derived : public Base{
    void foo(float){
    }
};

int main(){
    Derived d;
    d.foo(5);

    std::cin.get();
    return 0;
}


推荐答案

第10.2 / 2节


以下步骤定义类作用域中的名称查找结果, C 。首先,考虑类中的每个声明以及它的每个基类子对象。在一个子对象 B 中的成员名 f 隐藏成员名 f A 如果 A 是<$ c $的基类子对象c> B 隐藏的任何声明都会从考虑中删除。使用声明引入的每个声明都被认为是来自 C 的每个子对象,它是包含由使用声明指定的声明的类型-宣言。 如果生成的声明集不是全部来自相同类型的子对象,或者该集具有非静态成员并且包括来自不同子对象的成员,则存在歧义,强>。否则该集合是查找结果。

The following steps define the result of name lookup in a class scope, C. First, every declaration for the name in the class and in each of its base class sub-objects is considered. A member name f in one sub-object B hides a member name f in a sub-object A if A is a base class sub-object of B. Any declarations that are so hidden are eliminated from consideration. Each of these declarations that was introduced by a using-declaration is considered to be from each sub-object of C that is of the type containing the declara-tion designated by the using-declaration. If the resulting set of declarations are not all from sub-objects of the same type, or the set has a nonstatic member and includes members from distinct sub-objects, there is an ambiguity and the program is ill-formed. Otherwise that set is the result of the lookup.



class A {
public:
  int f(int);

};
class B {
public:
   int f();

};
class C : public A, public B {};
int main()
{
     C c;
     c.f(); // ambiguous
}

因此,您可以使用 using 声明 A :: f B :: f

So you can use the using declarations A::f and B::f to resolve that ambiguity

class C : public A, public B {
     using A::f;
     using B::f;

};

int main()
{
     C c;
     c.f(); // fine
}

第二个代码无缺陷地工作,因为 void foo(float)在C的范围内。实际上 d.foo(5); 调用 void foo(float)而不是 int 版本。

The second code works flawlessly because void foo(float) is inside C's scope. Actually d.foo(5); calls void foo(float) and not the int version.

这篇关于为什么具有相同名称但不同签名的多继承函数不会被视为重载函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆