我正在处理一个类,我的类中有 3 个数组,它们都代表相同的数据,但格式不同。我已经重载了<<
在我的类之外声明的运算符,它接受一个 const 引用而不是这个类的朋友。
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 种不同格式中的任何一种显示它。
是否有任何工作或解决此问题的方法?我希望能够将类对象发送给流运算符,而这些类型的运算符不能接受附加参数,因为它们是二元运算符而不是函数。