通常,如果嵌套类是在中声明的,则不可能访问它
private
#include <iostream>
#include <vector>
class Outer
{
private:
class Inner
{
public:
void sing() const { std::cout << "la la la\n"; }
void laugh() const { std::cout << "ha ha ha\n"; }
};
private:
std::vector<Inner> inners;
public:
void add() { inners.push_back(Inner()); }
};
int main()
{
auto o = Outer();
auto i = Outer::Inner(); // error: 'class Outer::Inner' is private within this context
}
Example on Wandbox
:
#include <iostream>
#include <vector>
class Outer
{
private:
class Inner
{
public:
void sing() const { std::cout << "la la la\n"; }
void laugh() const { std::cout << "ha ha ha\n"; }
};
private:
std::vector<Inner> inners;
public:
Inner & add() { inners.push_back(Inner()); return inners.back(); }
};
int main()
{
auto o = Outer();
auto i = o.add();
i.sing();
i.laugh();
}
Example on Wandbox
如果这是有效的,哪个规则允许此访问?
天真的,我会认为我不能坚持什么
Outer::add()
返回,或者最多可以保存它,但不能访问其成员。