gpt4 book ai didi

c++ - 为嵌套结构/类重载流插入运算符

转载 作者:太空宇宙 更新时间:2023-11-04 12:44:11 24 4
gpt4 key购买 nike

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

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;
}
};

关于c++ - 为嵌套结构/类重载流插入运算符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52546753/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com