注意:答案是按照特定的顺序给出的,但由于许多用户根据投票而不是给出的时间对答案进行排序,因此这里是答案的索引,它们是最有意义的顺序:
(注意:这是Stack Overflow的C++常见问题解答的一个条目.如果你想批评在这种形式下提供常见问题解答的想法,那么发布所有这些的元数据的发布将是这样做的地方.这个问题在C++聊天室中受到监控,其中FAQ的想法一开始就出现了,所以你的答案很可能被那些提出想法的人阅读.)
为什么我必须写,std::cout
而不是std::<<
像这样的代码行:
#include <iostream>
int main() {
std::cout << "Hello, world!";
return 0;
}
Run Code Online (Sandbox Code Playgroud)
cout
来自std
库,<<
通常不习惯进行位移?那么,为什么我::
之前也不必编写范围运算符<<
,因为它也用于其他含义?编译器如何知道后std::cout
,<<
意味着另一件事?
在编写测试套件时,我需要提供一个operator<<(std::ostream&...
Boost单元测试的实现来使用.
这有效:
namespace theseus { namespace core {
std::ostream& operator<<(std::ostream& ss, const PixelRGB& p) {
return (ss << "PixelRGB(" << (int)p.r << "," << (int)p.g << "," << (int)p.b << ")");
}
}}
Run Code Online (Sandbox Code Playgroud)
这没有:
std::ostream& operator<<(std::ostream& ss, const theseus::core::PixelRGB& p) {
return (ss << "PixelRGB(" << (int)p.r << "," << (int)p.g << "," << (int)p.b << ")");
}
Run Code Online (Sandbox Code Playgroud)
显然,当g ++尝试解决运算符的使用时,第二个未包括在候选匹配中.为什么(什么规则导致这个)?
代码调用operator<<
深入Boost单元测试框架,但这里是测试代码:
BOOST_AUTO_TEST_SUITE(core_image)
BOOST_AUTO_TEST_CASE(test_output) {
using namespace theseus::core;
BOOST_TEST_MESSAGE(PixelRGB(5,5,5)); // only compiles with operator<< definition inside theseus::core …
Run Code Online (Sandbox Code Playgroud)