【发布时间】:2019-01-20 07:40:21
【问题描述】:
考虑下面的例子
class base
{
protected :
int x = 5;
int(base::*g);
};
class derived :public base
{
void declare_value();
derived();
};
void derived:: declare_value()
{
g = &base::x;
}
derived::derived()
:base()
{}
据了解,只有基类的朋友和派生类可以访问基类的受保护成员,但在上面的示例中,我收到以下错误 "Error C2248 'base::x': cannot access protected member declared in class " 但是当我添加以下行时
friend class derived;
将其声明为朋友,我可以访问基类的成员,我在声明派生类时是否犯了一些基本错误?
【问题讨论】:
-
好吧,
derived的构造函数是私有的,所以这个类很难使用,但我认为这不是问题所在。为什么不尝试使用更简单的访问方式呢?例如,一个只返回x的派生类函数(提示:您无需指定base::即可访问它) -
stackoverflow.com/questions/477829/… 会回答您的问题吗?非常相似。
-
为什么不使用 just : g = &x; ?
-
@SebastianRedl 你链接的问题是关于在另一个实例上调用受保护的方法,这不是这里的情况
-
@user463035818 推理是一样的。您尝试通过不是您的类的访问路径访问受保护的成员。这就是为什么宋元瑶的回答有效。
标签: c++ class inheritance protected