【发布时间】:2013-08-12 07:31:46
【问题描述】:
我为 std::string 对象定义了运算符
std::string & operator<< (std::string & left, std::string & right){
return left += right;
}
然后我用它:
std::string t1("t1"), t2("t2"), t3;
t3 = t2 << t1;
并从编译器获取:
t.cpp: In function 'int main()':
t.cpp:44:28: error: no matching function for call to 'operator<<(std::string&, std::string&)'
t.cpp:44:28: note: candidates are:
In file included from d:\mingw\bin\../lib/gcc/mingw32/4.7.2/include/c++/iostream:40:0,
from connection.h:10,
from login.cpp:1:
d:\mingw\bin\../lib/gcc/mingw32/4.7.2/include/c++/ostream:600:5: note: template<class _CharT, class _Traits, class _Tp> std::basic_ostream<_CharT
, _Traits>& std::operator<<(std::basic_ostream<_CharT, _Traits>&&, const _Tp&)
d:\mingw\bin\../lib/gcc/mingw32/4.7.2/include/c++/ostream:600:5: note: template argument deduction/substitution failed:
t.cpp:44:28: note: 'std::string {aka std::basic_string<char>}' is not derived from 'std::basic_ostream<_CharT, _Traits>'
In file included from d:\mingw\bin\../lib/gcc/mingw32/4.7.2/include/c++/iostream:40:0,
为什么只谈 ostream 而不谈字符串? IE。为什么它不考虑我对运算符的定义
谢谢。
更新。对于那些只能说“为什么要为字符串创建 operator
std::string & operator<< (std::string & left, const int num){
return left += std::to_string(num);
}
std::string t3;
t3 << 3 << 5;
std::cout << t3 << std::endl;
并记录:
t.cpp: In function 'int main()':
t.cpp:45:12: error: no match for 'operator<<' in 't3 << 3'
t.cpp:45:12: note: candidates are:
In file included from d:\mingw\bin\../lib/gcc/mingw32/4.7.2/include/c++/iostream:40:0,
from connection.h:10,
from login.cpp:1:
d:\mingw\bin\../lib/gcc/mingw32/4.7.2/include/c++/ostream:600:5: note: template<class _CharT, class _Traits, class _Tp> std::basic_ostream<_CharT
, _Traits>& std::operator<<(std::basic_ostream<_CharT, _Traits>&&, const _Tp&)
d:\mingw\bin\../lib/gcc/mingw32/4.7.2/include/c++/ostream:600:5: note: template argument deduction/substitution failed:
t.cpp:45:12: note: 'std::string {aka std::basic_string<char>}' is not derived from 'std::basic_ostream<_CharT, _Traits>'
【问题讨论】:
-
为什么将
<<定义为字符串的+=?除了混淆阅读您的任何代码的任何人之外?什么目的? 字符串不是流。 -
就个人而言,我尝试在这种情况下添加括号。虽然我可能不明白到底发生了什么。
-
你确定你定义的算子在你尝试使用的时候是可用的吗?
-
@OlegG 无论如何,您是否尝试过准确地编译您向我们展示的内容(当然还有标准头文件)?如果它编译并正常工作,则错误在其他地方,我们看不到它。
-
@OlegG 你生成了一个最小的测试用例是对的,但不幸的是,这表明问题不是运算符重载所固有的。您应该在发布之前尝试过。