1

我想在提到的测试框架中输出我的类型。 谷歌明确表示这是可能的。

As mentioned earlier, the printer is extensible. That means you can teach it to do a better job at printing your particular type than to dump the bytes. To do that, define << for your type:

namespace foo {

class Bar { ... };

// It's important that PrintTo() is defined in the SAME
// namespace that defines Bar.  C++'s look-up rules rely on that.
void PrintTo(const Bar& bar, ::std::ostream* os) {
     *os << bar.DebugString();  // whatever needed to print bar to os
}

}  // namespace foo

我似乎已经这样做了。但是在尝试编译时,我得到以下信息:

error: no match for ‘operator<<’ in ‘* os << val’ /usr/include/c++/4.4/ostream:108: note: candidates are:

紧随其后的是一长串提案,operator<<最后我的超载:

std::ostream& Navmii::ProgrammingTest::operator<<(std::ostream&, Navmii::ProgrammingTest::AsciiString&)

有人可以帮忙吗?

4

1 回答 1

1

您似乎已经operator<<为非常量AsciiString对象定义了。无论 Google 试图打印什么,都可能是 const。将第二个参数作为 const 引用传递,因为您不应该修改打印的值:

std::ostream& Navmii::ProgrammingTest::operator<<(
  std::ostream&,
  Navmii::ProgrammingTest::AsciiString const&);

这与链接文档中的代码更匹配。但是,问题中的引文中省略了该部分。

问题引用了这个PrintTo例子。该代码很好,但我认为这并不是您在自己的代码中真正所做的。正如文档所说,PrintTo如果您不想提供operator<<,或者如果operator<<您的类不适合在单元测试期间进行调试输出,则可以使用。

于 2012-11-27T16:36:57.430 回答