本文介绍了不明确的访问的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

可能的重复:
为什么要做多继承函数名称相同但签名不同的函数不会被视为重载函数?

我收到一个错误:

ambiguous access of 'attach'
    could be the 'attach' in base 'A::A1'
    or could be the 'attach' in base 'B::B1'

这是代码:

class A
{
public:
    class A1
    {
    public:
        virtual void attach( A & a ) { }
    };
public:
};

class B
{
public:
    class B1
    {
    public:
        virtual void attach( B & b ) { }
    };
public:
};

class C : public A::A1, public B::B1
{
public:
    C(){ }
};

void main(int argc, char *argv[])
{
    A a;
    B b;
    C c;
    c.attach( a );
    c.attach( b );
}

我理解错误.编译器很困惑,它想要范围:

I understand the error. The compiler is confused, it wants scope:

c.A::A1::attach( a );
c.B::B1::attach( b );

这种语法太可怕了.我可以在 C 中定义附加方法,现在编译器得到它,但我不想定义所有这些附加方法:

That syntax is horrible. I can define the attach methods in C, and now the compiler gets it, but I don't want to have to define all of these attach methods:

class C : public A::A1, public B::B1
{
public:
    C(){ }
void attach( A & a ) { A::A1::attach(a); }
void attach( B & b ) { B::B1::attach(b); }
};

谁能向我解释为什么编译器在很清楚(在我看来)应该使用哪个附加"时对附加"感到困惑?谁能提供不需要范围界定的解决方案?

Can anyone explain to me why the compiler is confused about 'attach' when it is clear (in my mind) which 'attach' should be used? Can anyone offer a solution that does not require scoping?

UPDATE:在我的第二个 C 示例中更新了范围,例如A::A1::attach(a)

UPDATE: updated the scope in my second C example, e.g. A::A1::attach(a)

更新:在调查下面提到的重复时,我遇到了解决方案:

UPDATE: when investigating the duplicate noted below, I came across the solution:

class C : public A::A1, public B::B1
{
public:
    using A::A1::attach;
    using B::B1::attach;
public:
    C(){ }
};

在我作为 C++ 程序员的 18 年里,我从来没有像这样使用过使用".我什至不知道它存在.

In my 18 years as a c++ programmer, I've never had to use 'using' like that. I didn't even know that existed.

推荐答案

此功能是为了避免 Fragile Base Class 问题.考虑一下如果这按您的预期工作会发生什么 - 然后 A::A1 添加一个采用 B::B1 引用的重载.突然间,您的所有呼叫站点都变得模棱两可——即使您没有做任何更改.如果重载是私有的,则甚至都是如此.

This feature is to avoid the Fragile Base Class problem. Consider what would happen if this worked as you expected- and then A::A1 adds an overload taking a B::B1 reference. Suddenly, all your call sites are ambiguous- even though you didn't change anything. This is even true if the overload is private.

当然,在我看来,这是非常没有意义的,因为有上百万种其他方法可以破坏您的派生类和其他问题.但这就是明显的理由.

Of course, in my opinion, this is highly pointless, since there are a million other ways you can break your derived classes and other problems. But that's the apparent rationale.

这篇关于不明确的访问的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-18 14:24