c++ - 派生类无法访问基类的受保护成员
问题描述
考虑以下示例
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;
将它声明为朋友,我可以访问基类的成员,我在声明派生类时是否犯了一些基本错误?
解决方案
派生类protected
只能通过派生类的上下文访问基类的成员。换句话说,派生类不能通过protected
基类访问成员。
当形成指向受保护成员的指针时,它必须在其声明中使用派生类:
struct Base { protected: int i; }; struct Derived : Base { void f() { // int Base::* ptr = &Base::i; // error: must name using Derived int Base::* ptr = &Derived::i; // okay } };
你可以改变
g = &base::x;
至
g = &derived::x;
推荐阅读
- c# - 如何在 C# 中将小数点的输入限制为仅 1?
- javascript - 你好,我是编码新手,我想知道如何让输出水平而不是垂直
- spring-boot - 无法从应用程序 yml 解析 feign 客户端名称
- android - 在 android Studio 中找不到 MainActivity.Kt 和 activity_main.xml
- flutter - TextFormField Validator:错误边框未激活
- sql - 无法识别雪花时间戳“2015 年 1 月 23 日 23:02:39”中的日期时间
- drake - Nightly build 未获得 mosek 许可证
- php - PHP PDO SQL Server 无法通过 Ubuntu 终端连接
- network-programming - `select` 是否处理多个端点或多个套接字?
- excel - Excel函数自动递增