gpt4 book ai didi

C++ 重载 I/0 运算符 : Getting Past Ambiguity

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

我正在上课,我的课上有 3 个数组,它们都代表相同的数据,但格式不同。我已经重载了 <<在我的类之外声明的运算符采用常量引用而不是此类的友元。

SomeClass {
public:
// Nameless Union - All 3 Arrays Are of The Same Exact Data Type
// And All 3 Arrays Have The Same Exact Size. This Nameless Union
// Uses The Same Memory Address For All 3 Arrays And Their Elements.
// So An Element Is Changed By One Array Type, It Is Expected And
// Accepted For It To Change The Others. This Is Not 3 Different
// Arrays, This Is Still 1 Array Of Size 256, Just Different
// Representations Or Different Ways To Access Them.
union {
int m_256[256];
int m_16[16][16];
int m_4[4][4][4][4];
};

SomeClass() { std::fill( std::begin( m_256 ), std::end( m_256 ), 0 ); }

}; // SomeClass

std::ostream& operator<<( std::ostream& out, const SomeClass& c ) {
out << std::endl;

for ( unsigned box = 0; box < 4; box++ ) {
for ( unsigned slice = 0; slice < 4; slice++ ) {
for ( unsigned row = 0; row < 4; row++ ) {
for ( unsigned col = 0; col < 4; col++ ) {
out << "(" << box << "," << slice << "," << row << "," << col << ") = "
<< c.m_4[box][slice][row][col] << std::endl;
}
}
}
}
return out;
} // operator<<

这是我目前拥有的。我希望能够做的是也使用 operator<<也使用此类,但能够区分以不同格式显示相同数据的方式。

我知道你不能这样做:通过添加第二个

std::ostream& operator<<( std::ostream& out, const SomeClass& c ) {
out << std::endl;
for ( unsigned i = 0; i < 16; i++ ) {
for ( unsigned j = 0; j < 16; j++ ) {
out << "(" << i << "," << j << ") = " << c.m_16[i][j] << std::endl;
}
}
return out;
} // operator<<

第三个

std::ostream& operator<<( std::ostream& out, const SomeClass& c ) {
out << std::endl;
for ( unsigned u = 0; u < 256; u++ ) {
out << u << " = " << m_256[u] << std::endl;
}
return out;
} // operator<<

由于这是模棱两可的。然而,我希望能够以 3 种不同格式中的任何一种显示它。

这个问题是否有任何工作或解决方案?我希望能够将类对象发送到流运算符,这些类型的运算符不能接受额外的参数,因为它们是二元运算符而不是函数。

最佳答案

您可以只使用适配器类来编写输出。您可以将格式说明符传递给构造函数或按类型区分。例如(按类型区分):

struct SomeClassAs256 {
SomeClass const& x_;

explicit(SomeClass const& x) : x_(x) {}
};

然后有一个运算符<<实现:

ostream& operator<<(ostream& os, SomeClassAs256 const& x) {
...
return os;
}

然后你使用它:

SomeClass x;
...
cout << SomeClassAs256(x) << endl;

关于C++ 重载 I/0 运算符 : Getting Past Ambiguity,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36492699/

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