关于这个主题有几篇帖子,但我认为这是最简单的例子之一,希望它能澄清一些关于cout和初始化的事情。
这样可行:
class A {
public:
std::ostream& operator<< (std::ostream& os) {
return os;
}
};
class B {
std::ostream& operator<< (std::ostream& os) {
A a(); // <-- LOOK
std::cout << a;
return os;
}
};
但如果我只是A a()
到A a
:
class A {
public:
std::ostream& operator<< (std::ostream& os) {
return os;
}
};
class B {
std::ostream& operator<< (std::ostream& os) {
A a; // <-- LOOK
std::cout << a;
return os;
}
};
它抛出:
nvcc main.cpp util.cpp -o main -lcublas -std=c++11
In file included from main.cpp:9:0:
cout-test.hpp: In member function ‘std::ostream& B::operator<<(std::ostream&)’:
cout-test.hpp:21:20: error: cannot bind ‘std::ostream {aka std::basic_ostream<char>}’ lvalue to ‘std::basic_ostream<char>&&’
std::cout << a;
^
In file included from /usr/include/c++/4.8/iostream:39:0,
from main.cpp:5:
/usr/include/c++/4.8/ostream:602:5: error: initializing argument 1 of ‘std::basic_ostream<_CharT, _Traits>& std::operator<<(std::basic_ostream<_CharT, _Traits>&&, const _Tp&) [with _CharT = char; _Traits = std::char_traits<char>; _Tp = A]’
operator<<(basic_ostream<_CharT, _Traits>&& __os, const _Tp& __x)
^
make: *** [main] Error 1
如果我让A a
成为一名成员,我会得到同样的错误:
class B {
A a; // <-- LOOK
std::ostream& operator<< (std::ostream& os) {
std::cout << a;
return os;
}
};
是什么给出了?
答案 0 :(得分:1)
第一个案例
A a();
不构造对象。它声明了一个函数。此解析问题称为The Most Vexing Parse。
A a();
std::cout << a;
有效,因为在这种情况下a
会转换为bool
。请参阅Why does pointer to int convert to void* but pointer to function convert to bool?为何有效。
第二种情况
A a;
std::cout << a;
由于您定义operator<<
函数的方式,不起作用。你必须使用
A a;
a << std::cout;
operator<<
函数需要是非成员函数才能使用:
A a;
std::cout << a;
请参阅my answer to another SO post了解原因。