Overcoming diamond ambiguity in different way

不问归期 提交于 2019-12-12 09:40:03

问题


I know the diamond problem and method to solve it using virtual base class. I tried to solve diamond problem in a different way but did not succeed. I don't know why.

#include <iostream>

using namespace std;
class A
{
    public:
       void display()
       {
           cout << "successfully printed";
       }
};

class B: public A
{

};

class C: private A // display() of A will become private member of C
{

};

class D: public B, public C // private member display() of C should not be inherited
{

};

int main()
{
    D d;
    d.display();
    return 0;
}

As the private members are not inherited the class D will not inherit any function from C, and when class D inherit class B and C, there should only 1 display() function in D. But when I try to access display() function using object of class D, it is showing same problem that display function is ambiguous.


回答1:


"Private members are not inherited" is a false premise, this isn't Java.

Member access in C++ was designed in such a way that if you replace any private: with public:, the behavior of the program will not change.

Because of that, name lookup, which occurs here when the compiler encounters the name "display" in d.display(), first locates all member functions in d with that name (there are two), then finds the best match (failure here), and only then checks if it happens to be inaccessible due to member access rules.



来源:https://stackoverflow.com/questions/26740893/overcoming-diamond-ambiguity-in-different-way

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!