如何比较 C++ 中的两个 ostream 对象为了平等?
我在类中重载了左移运算符,并且输出工作正常,因此例如当我有一行内容为 cout <<对象;我将输出用逗号分隔的字段。
ostream& operator<<(ostream& output, const MyClass& obj)
{
output << obj.field1 << ", " << obj.field2;
return output;
}
我想为此操作编写一个测试用例,但我不知道如何将返回结果与cxxtest中的预期结果进行比较。我尝试了以下操作,但它不起作用:
TS_ASSERT_EQUALS(cout << "1, 50.0", cout << obj);
我应该使用不同的 cxxtest 操作或更改 TS_ASSERT_EQUALS 中的参数传递机制吗?
请注意,当我输出以下几行时,我得到相同的结果:
cout << obj;
cout << "1, 50.0";
注意:当我尝试编译程序时,由于 TS_ASSERT_EQUALS 失败,我收到一堆编译器错误。
I overloaded the left shift operator in my class and the output works fine, so for example when I have a line which says cout << obj; I will output the fields seperated by a comma.
ostream& operator<<(ostream& output, const MyClass& obj)
{
output << obj.field1 << ", " << obj.field2;
return output;
}
I want to write a test case for this operation, but I have no idea how to compare the returned result with the expected result in cxxtest. I tried the following, but it did not work:
TS_ASSERT_EQUALS(cout << "1, 50.0", cout << obj);
Am I supposed to use a different cxxtest operation or change the parameter passing mechanism in TS_ASSERT_EQUALS?
Note that when I output the following lines, I get the same results:
cout << obj;
cout << "1, 50.0";
Note: I get a bunch of compiler errors when I attempt to compile the program because TS_ASSERT_EQUALS fails.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
即使它确实编译了,您基本上也是在将
cout
与其自身进行比较...尝试写入两个不同的
std::stringstream
,提取它们的字符串值,然后比较它们。如果您还需要测试 ostream 标志,请定义比较函数并使用
TS_ASSERT_RELATION
。Even if it did compile, you're basically comparing
cout
with itself ...Try writing to two distinct
std::stringstream
s, extracting their string values, and comparing these.If you also need to test ostream flags, define a comparison function and use
TS_ASSERT_RELATION
.