(Oktalist在下面给出了一个很好的答案,查看它下面的评论,以帮助演示我们讨论的所有内容,我在问题的底部添加了一个完整的编译解决方案,演示了所讨论的所有内容.)
我有一组命名空间全局方法和模板化方法,如下所示:
namespace PrettyPrint
{
String to_string(bool val);
String to_string(char val);
String to_string(int val);
String to_string(uint val);
// ETC...
template <typename T> String to_string(const T* val)
{
if (! val) return U("NULL");
return String().copy_formatted("(%p)-> %S", (const void*)val, to_string(*val).uchars());
}
// ... and more templates to help with containers and such
}
Run Code Online (Sandbox Code Playgroud)
"String"类型不是C++字符串,它是从IBM的ICU库派生的特殊类,但与此问题并不真正相关.重点是,我有一堆称为to_string的命名空间全局方法,还有一些覆盖它们的模板化函数.到目前为止,这么好,一切都很好.但是,现在我有另一个标题,我有类似下面的定义:
namespace User
{
struct Service {
int code;
String name;
}
//...
}
namespace PrettyPrint
{
String to_string(const User::Service& val) { return val.name; }
}
Run Code Online (Sandbox Code Playgroud)
所以,现在我已经在其他地方定义了一些其他类型,我还在PrettyPrint命名空间中定义了另一个to_string覆盖,以指示如何将我的新类型转换为String.将两个标题放入文件中,如下所示:
#include <the …Run Code Online (Sandbox Code Playgroud) include <stdio.h>
class Base
{
protected:
int foo;
int get_foo() { return foo; }
};
class Derived : public Base
{
public:
void bar()
{
int Base::* i = &Base::foo;
this->*i = 7;
printf("foo is %d\n", get_foo());
}
};
int main()
{
Derived d;
d.bar();
}
Run Code Online (Sandbox Code Playgroud)
我不明白为什么我的派生类型不能指向基类的受保护成员.它有权访问该成员.它可以调用类似范围的函数.为什么它不能成为成员指针?我正在使用gcc 4.1.2,我收到此错误:
test.cc: In member function ‘void Derived::bar()’:
test.cc:6: error: ‘int Base::foo’ is protected
test.cc:15: error: within this context
Run Code Online (Sandbox Code Playgroud)