为什么派生类未能访问基类的受保护成员



Talk很便宜,给你看代码:

#include <string>
#include <vector>
using namespace std;
class Message {
protected:
virtual string json() const = 0;
};
class _messageChain_ final: public Message {
public:
string json() const override;
private:
vector<Message *>messages;
};
string _messageChain_::json() const
{
string json;
for ( Message *msg : messages )
json += msg->json();
return json;
}
int main ( void )
{
}

当我试图编译它时:

main.cpp: In member function ‘virtual std::string _messageChain_::json() const’:
main.cpp:21:21: error: ‘virtual std::string Message::json() const’ is protected within this context
21 |   json += msg->json();
|                     ^
main.cpp:7:17: note: declared protected here
7 |  virtual string json() const = 0;

我认为protected将使_messageChain_能够在函数string _messageChain_::json()const;中访问Message的成员(virtual string json();(。

但事实并非如此。

如果我将_messageChain_添加为Message的朋友,或者将protected替换为public,它将起作用。如果我将string _messageChain_::json()const;添加为好友,它将不起作用。

我很困惑为什么protectedfriend <function>不起作用,而friend class _messageChain起作用。

来自Protected_member_access(emphasis mine(:

类的受保护成员只能访问

  1. 致该班的成员和朋友
  2. 对于该类的任何派生类的成员,,但仅当访问受保护成员的对象的类是派生类或该派生类的派生类时

因此您只能从_messageChain_对象访问Message::json

最新更新