gpt4 book ai didi

c++ - 为什么我不能访问作为参数传递给函数的基类的 protected 成员变量?

转载 作者:可可西里 更新时间:2023-11-01 18:16:14 29 4
gpt4 key购买 nike

This答案似乎表明它应该可以工作,那么为什么我的示例会引发编译器错误:

class Class1
{
protected:
long m_memberVar;
};

class SubClass1: public Class1
{
public:
void PrintMember(Class1 memberToPrintFrom)
{
Console::Write("{0}", memberToPrintFrom.m_memberVar); // <-- Compiler error: error C2248: 'BaseClassMemberAccess::Class1::m_memberVar' : cannot access protected member declared in class 'BaseClassMemberAccess::Class1'
}
};

[编辑] - 根据 Need4Sleep 的建议将子类更改为公共(public)继承,但这没有区别。

最佳答案

在这个答案中,我假设您在代码中使用了 public 继承(问题中没有)。


[C++11: 11.2/1]: If a class is declared to be a base class (Clause 10) for another class using the public access specifier, the public members of the base class are accessible as public members of the derived class and protected members of the base class are accessible as protected members of the derived class. If a class is declared to be a base class for another class using the protected access specifier, the public and protected members of the base class are accessible as protected members of the derived class. If a class is declared to be a base class for another class using the private access specifier, the public and protected members of the base class are accessible as private members of the derived class.

这涵盖了您正在访问同一 对象的成员的情况。

但是,对于 protected 成员访问有点好奇,为了访问 another 对象的 protected 成员,它必须是位于相同类型或更派生类型的定义内;在您的情况下,它是派生较少的类型(即基础):

[C++11: 11.4/1]: An additional access check beyond those described earlier in Clause 11 is applied when a non-static data member or non-static member function is a protected member of its naming class (11.2) As described earlier, access to a protected member is granted because the reference occurs in a friend or member of some class C. If the access is to form a pointer to member (5.3.1), the nested-name-specifier shall denote C or a class derived from C. All other accesses involve a (possibly implicit) object expression (5.2.5). In this case, the class of the object expression shall be C or a class derived from C.

也就是说,您必须从 Class1 成员函数中运行此代码。

Bjarne 在他的书 The C++ Programming Language (Sp. Ed.) 第 404 页提到了这一点:

A derived class can access a base class' protected members only for objects of its own type [...] This prevents subtle errors that would otherwise occur when one derived class corrupts data belonging to other derived classes.

关于c++ - 为什么我不能访问作为参数传递给函数的基类的 protected 成员变量?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13723217/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com