【发布时间】:2020-07-09 15:24:15
【问题描述】:
假设我有一个包含 A 类数组的 B 类,我想使用 std::wostringstream 输出 B 类中的数据。我已经为 Class 重载了运算符 << B,但我只收到“E0349”和“C2679”错误。
A类的定义
class A
{
public:
A();
~A();
inline A(float _x, float _y, float _z) :
x(_x), y(_y), z(_z)
{
}
inline void Set(float _x, float _y, float _z);
float x, y, z;
friend std::ostream& operator<<(std::ostream& out, const A& source);
friend std::wostringstream& operator<<(std::wostringstream& out, const A& source);
private:
};
B类的定义
class B
{
public:
A* ArrayOfA;
bool Initialize(const A* samples,
unsigned int count);
friend std::wostringstream& operator<<(std::wostringstream& out, const B& source);
B();
~B();
private:
};
如您所见,B 类有一个 A 类数组。
我已经为 A 类重载了运算符 <<。
std::wostringstream&
operator<<(std::wostringstream& out, const A& source)
{
out << '<' << source.x << ',' << source.y << ',' << source.z << '>';
return out;
}
现在,我想使用 B 类:
std::wostringstream wss;
wss << ClassB
但我做不到。
这是错误代码,我为 B 类重载了运算符 <<
std::wostringstream&
operator<<(std::wostringstream& out, const B& source)
{
for (unsigned int i = 0; i < 4; ++i)
{
out << ":" << source.ArrayOfA[i] << std::endl;
// ERROR:E0349 no operator "<<" matches these operands
// ERROR:C2679 binary '<<' : no operator found which takes a right-hand operand of type'A' (or there is no acceptable conversion)
}
return out;
}
这是完整的代码。它是在线编译器。
A little bit of long code sample, but with details
完整的代码在 URL 中。
怎么了?您将如何将 ArrayOfA 发送到 std::wostringstream?如果你只使用std::ostream,你将如何获得像std::wostringstream这样的字符串内容?我的运算符重载有什么问题吗?
【问题讨论】:
-
请将您的代码作为问题的一部分以文本形式发布,并以最小的可重现示例形式发布。
-
可能
A没有<<过载,但无法确定给出的内容。我们可以找您联系minimal reproducible example 吗?制作 MRE 很有可能会在没有任何进一步帮助的情况下引导您找到解决方案。 -
Stack Overflow 的目标是构建一个未来程序员可以使用的问题和答案存储库。链接腐烂,这不可能。为什么我们要求minimal reproducible example:它是强大调试技术的升华。很难做出好的 MRE 却找不到解决问题的方法。如果您正在寻求帮助调试并且您还没有使用 MRE 或类似的东西隔离问题,那么您就是在浪费时间。
-
我添加了更多细节。感谢所有建议。
-
我添加了更多细节。感谢所有建议。
标签: c++ operator-overloading ostream wostringstream