Private inheritance: name lookup error

怎甘沉沦 提交于 2019-11-30 13:56:19

问题


I have the following code example that doesn't compile:

#include <stdio.h>

namespace my
{
    class base1
    { // line 6
    };

    class base2: private base1
    {
    };

    class derived: private base2
    {
    public:
        // The following function just wants to print a pointer, nothing else!
        void print(base1* pointer) {printf("%p\n", pointer);}
    };
}

The error that gcc prints is:

test.cpp:6: error: `class my::base1' is inaccessible

test.cpp:17: error: within this context

Now, i can guess what the problem is: when looking at the declaration of print, the compiler sees base1 and thinks: base1 is the base-class subobject of derived* this, but you don't have access to it! While i intend that base1 should be just a type name.

How can i see in the C++ Standard that this is a correct behavior, and not a bug in the compiler (i am sure it's not a bug; all compilers i checked behaved so)?

How should i fix this error? All the following fixes work, but which one should i choose?

void print(class base1* pointer) {}

void print(::my:: base1* pointer) {}

class base1; void print(base1* pointer) {}


Edit:

int main()
{
    my::base1 object1;
    my::derived object3;
    object3.print(&object1);
}

回答1:


The section you're looking for is 11.1. It suggests using ::my::base1* to work around this:

[ Note: In a derived class, the lookup of a base class name will find the injected-class-name instead of the name of the base class in the scope in which it was declared. The injected-class-name might be less accessible than the name of the base class in the scope in which it was declared. — end note ]

[ Example:
class A { };
class B : private A { };
class C : public B {
A *p;
// error: injected-class-name A is inaccessible
:: A * q ;
// OK
};


来源:https://stackoverflow.com/questions/5634637/private-inheritance-name-lookup-error

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