2016-09-07 92 views
2

我有一个继承的问题: 比方说,我有C++继承 - 暧昧功能

class Time{ 
protected: 
void foo(); 
}; 

class Base: private Time{ 
void foo1(){ foo(); } 
}; 

class Child: public Base, private Time{ 
void foo2(){ foo(); }// here my compiler says that foo is ambiguous 
}; 

为什么FOO()不明确,如果继承在基地的时间是私人的?

PS。 只需要&仅适用于需要查看完整代码的人员,以下是GitHub项目: https://github.com/huntekah/Interior_decorator-OpenGL_Project/blob/master/Grafika-OpenGL/Interior_decorator/Display.cpp#L133 class Control(实用程序目录)由ControlObjects和ControlCamera继承,它们都是Controls的基础。显示继承控件,另外还有时间。注释行显示SetDeltaTime()不明确的地方;

+0

私人不会隐藏它。 – Jarod42

+0

因为'Base'和'Time'都有一个名为'foo'的成员函数,编译器不知道你试图调用哪一个函数。这里有一个这样的地方。将基地里面的命名空间隐藏起来吗 –

+0

? –

回答

0

开场白

您的代码段不能编译的另一个原因是:BaseTimefoo()进不去,因为它是一个私有成员。所以foo1()导致一个错误,在你有歧义之前。

如果更改Time使其成员的保护,那么你就可以复制你的错误正是你描述:

class Time{ 
protected: 
    void foo(); 
}; 

这里有什么错?

Base私下继承Time,以便它的成员不被外界看到。

但是,对于外部世界来说,对派生类来说可能是这样。在推导的情况下,名称查找规则说,第一个名字是在类层次抬头,然后重载应用,不是仅仅是访问控制进行:

10.2/1 Member name lookup determines the meaning of a name (id-expression) in a class scope. Name lookup can result in an ambiguity, in which case the program is ill-formed. For an id-expression, name lookup begins in the class scope of this; for a qualified-id, name lookup begins in the scope of the nested-name-specifier. Name lookup takes place before access control.
10.2/8 If the name of an overloaded function is unambiguously found, overloading resolution also takes place before access control. Ambiguities can often be resolved by qualifying a name with its class name.

当你使用多重继承:

Time  
    : 
    : 
Base Time 
    \ : 
    \ : 
    Child 

因此,您继承了两次foo(),一次通过私有继承和onve通过公共。根据标准,这种歧义使得名称foofoo2()不明确,并且在验证访问权限之前,使您的代码无效。

请注意,Child会看到2 foo(),但具有讽刺意味的是,它们都不能使用它们:都通过私有继承来实现。所以,即使你解决了歧义,你也会得到另一个关于可访问性的错误信息。

1

你的代码还有另一个错误:类的基类从类时间和类私下继承孩子从类时间私下继承!

继承法:

class Time 
{}; 

class Base : private Time 
{}; 

class Child : public Base, private Time 
{}; 

基地拥有上课时间的副本,因为它是从它继承。

孩子有一个类Base的副本,因为它从它继承。

***孩子拥有Time类的副本,因为其父母(基地)拥有此副本。

如果Child试图从类显式继承时间将发出编译时错误:错误C2584:'孩子':直接基'时间'是不可访问的;已经是'基地'的基地