友元类如何访问嵌套类的私有成员
How a friend class can access a private member of a nested class?
请考虑以下示例:
class SIP{
public:
friend std::ostream& operator<<(std::ostream& os, const SIP& c);
private:
class BusStop;
std::vector<BusStop*> mbusStops;
};
class SIP::BusStop{
private:
struct BusInfo;
std::vector<BusInfo*> mbusStopTerminal;
};
struct SIP::BusStop::BusInfo{
std::string from;
std::string to;
};
std::ostream& operator<<(std::ostream &os, const SIP &c) {
for (std::vector<SIP::BusStop*>::const_iterator it = c.mbusStops.begin();
it != c.mbusStops.end(); it++){
for (std::vector<SIP::BusStop::BusInfo*>::const_iterator it2 = mbusStopTerminal.begin();
it2 != mbusStopTerminal.end(); it2++){
}
}
return os;
}
它不会编译,因为 BusInfo 结构是私有的。默认情况下,友元类无法访问嵌套类的私有成员。在这种情况下我该怎么办?有什么解决方法吗?
您可以向SIP
添加一个停止打印功能:
class SIP{
public:
friend std::ostream& operator<<(std::ostream& os, const SIP& c);
private:
void printStops(std::ostream& os);
class BusStop;
std::vector<BusStop*> mbusStops;
};
std::ostream& operator<<(std::ostream &os, const SIP &c) {
c.printStops(os);
return os;
}
或者你可以一直添加运算符:
class SIP{
public:
friend std::ostream& operator<<(std::ostream& os, const SIP& c);
private:
class BusStop;
std::vector<BusStop*> mbusStops;
};
class SIP::BusStop{
private:
friend std::ostream& operator<<(std::ostream& os, const BusStop& c);
struct BusInfo;
std::vector<BusInfo*> mbusStopTerminal;
};
struct SIP::BusStop::BusInfo{
std::string from;
std::string to;
};
std::ostream& operator<<(std::ostream &os, const SIP::BusStop::BusInfo &i)
{
// Whatever
}
std::ostream& operator<<(std::ostream &os, const SIP::BusStop &c)
{
for (std::vector<SIP::BusStop::BusInfo*>::const_iterator it = mbusStopTerminal.begin();
it != mbusStopTerminal.end(); it++){
os << **it;
}
}
std::ostream& operator<<(std::ostream &os, const SIP &c) {
for (std::vector<SIP::BusStop*>::const_iterator it = c.mbusStops.begin();
it != c.mbusStops.end(); it++){
os << **it;
}
return os;
}
或适合您的代码的任意方法组合。
相关文章:
- 嵌套在类中时无法设置成员数据
- 如何在 C++ 的外部类构造函数中初始化嵌套类成员
- 迭代嵌套映射与范围为循环:没有名为"first"的成员
- 如何从另一个嵌套类中调用某个封闭类的嵌套类的函数指针成员的值?
- MSVC 2017 - 错误 - 如何将模板类 X 的模板成员函数声明为嵌套类 X::Y 的好友
- std::void_t 和嵌套的非类型成员
- C2436 '{ctor}':构造函数初始值设定项列表中的成员函数或嵌套类
- c++ 嵌套结构映射找不到成员
- 无法从多态嵌套类访问包含类的成员
- 其他类的成员函数对成员函数的嵌套引用
- 如何从嵌套在命名空间中的类调用成员函数?
- 返回自身内部的双重嵌套类的成员函数,该类继承自从自身继承的类
- 嵌套的类成员变量不可访问.链表设置.V、下一个和新的问题
- 当使用嵌套类功能时,使用非静态数据成员的使用无效,但是当函数未固定时可以
- 包含指针成员的嵌套结构
- 缩短成员函数作用域说明符(嵌套类)(C++)
- 为什么嵌套类的成员函数不需要完整类型?
- 使用泛型函数调用打印结构的所有嵌套成员变量
- 嵌套成员类型识别
- 初始化构造函数中嵌套成员的语法