重载嵌套结构/类的流插入运算符

Overload the stream insertion operator for nested structures/classes

本文关键字:插入 运算符 嵌套 结构 重载      更新时间:2023-10-16

我想重载嵌套在类中的结构的流插入运算符。如何修复此错误并使函数正常工作,或者是否有任何替代方法来实现它?

struct S {
int a;
int b;
};
class T {
private:
S** arrayName;
int r;
int c;
public:
friend ostream& operator << (ostream& _os, const T& _t) {
for (int i = 0; i < _t.r; i++) {
for (int j = 0; j < _t.c; j++) {
_os << _t.arrayName[i][j];
}
}
return _os;
}
}

如果arrayName只是class T中的整数数组,如下所示:

int arrayName [4][4]; //for example

当前的实现将起作用。但是由于arrayName是一个指向struct S的指针,并且充当struct S的二维数组,因此您需要在struct S内重载<<运算符才能ab打印其成员。

所以你的struct S现在应该是:

struct S {
int a;
int b;
friend ostream& operator<<(ostream& _os, const S& _s) { 
_os << _s.a << ' ' << _s.b << endl; 
return _os; 
}
};