我有以下不编译的代码示例:
#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);}
    };
}
gcc打印的错误是:
test.cpp:6:错误:`class my :: base1'无法访问
test.cpp:17:错误:在此上下文中
现在,我可以猜出问题是什么:在查看声明时print,编译器会看到base1并认为:base1是基类子对象derived* this,但是您无法访问它!虽然我打算这base1应该只是一个类型名称.
我怎么能在C++标准中看到这是一个正确的行为,而不是编译器中的错误(我确定它不是一个错误;我检查过的所有编译器都表现得如此)?
我该如何解决这个错误?所有以下修复工作,但我应该选择哪一个?
void print(class base1*pointer){}
void print(:: my :: base1*pointer){}
class base1; void print(base1*pointer){}
编辑:
int …此代码示例将描述我发现非直观的语言功能.
class A {
public:
  A() {}
};
class B: private A
{
public:
  B() {}
};
class C: public B
{
public:
  C() {}
  void ProcessA(A* a) {
  }
};
int main() {
  C c;
}
在Mac上使用Apple LLVM 4.2版编译此代码会产生一个
test.cc:16: error: ‘class A’ is inaccessible
test.cc:16: error: within this context
更换void ProcessA(A* a)与void ProcessA(::A* a)将使建立,但我不明白为什么我要在这里使用绝对类名.它是一种语言功能,可以避免某些错误,或者它只是一个黑暗的C++语法角,就像要求> >在与其他模板参数化的模板中的尖括号()之间放置空格.谢谢!
使用g ++ 4.2.1编译此代码:
struct S { };
template<typename T> struct ST { };
template<typename BaseType>
class ref_count : private BaseType { };
template<typename RefCountType>
class rep_base : public RefCountType { };
class wrap_rep : public rep_base<ref_count<S> > {
  typedef rep_base<ref_count<S> > base_type;      // line 11
};
我明白了:
bug.cpp:1: error: ‘struct S’ is inaccessible
bug.cpp:11: error: within this context
但是,如果我更改wrap_rep要使用的类ST:
class wrap_rep : public rep_base<ref_count< ST<int> > > {
  typedef rep_base<ref_count< ST<int> > > base_type;
};
它编译得很好.或者,如果我将原始代码更改为: …