为何C++非友元嵌套类构造函数可访问外部类私有成员?
为什么这段嵌套类代码能访问外部类的私有静态成员
你之前的认知有偏差:C++中嵌套类作为外部类的成员,天生就有权访问外部类的所有静态成员(包括私有静态成员),不需要额外声明为友元类。
具体到这段代码:
Something::_nested是Something的公有嵌套类,属于Something的成员范畴。s_mychars是Something的私有静态成员,静态成员属于整个类而非单个对象,嵌套类在自己的作用域内可以直接访问外部类的静态成员,不受私有访问权限的限制。_nested的构造函数操作Something::s_mychars完全符合C++的访问规则,所以代码能正常编译运行。
补充一点:如果要访问外部类的非静态私有成员,嵌套类就需要持有外部类的对象实例(比如通过构造函数传入外部类对象的指针/引用),因为非静态成员属于特定对象,而非类本身。
#include <iostream> #include <vector> class Something { private: static std::vector<char> s_mychars; public: class _nested { public: _nested() { s_mychars.push_back('o'); s_mychars.push_back('a'); s_mychars.push_back('u'); s_mychars.push_back('i'); s_mychars.push_back('e'); } }; static void getSomething() { for (auto const &element : s_mychars) std::cout << element << ' '; } private: static _nested s_initializer; }; std::vector<char> Something::s_mychars; Something::_nested Something::s_initializer; int main() { Something::getSomething(); return 0; }
内容的提问来源于stack exchange,提问作者coyne
相关产品推荐
相关产品推荐

