如何比较 C++ 中的两个 ostream 对象为了平等?

发布于 2024-10-01 01:03:27 字数 645 浏览 1 评论 0原文

我在类中重载了左移运算符,并且输出工作正常,因此例如当我有一行内容为 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

你げ笑在眉眼 2024-10-08 01:03:27

即使它确实编译了,您基本上也是在将 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::stringstreams, extracting their string values, and comparing these.

If you also need to test ostream flags, define a comparison function and use TS_ASSERT_RELATION.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文