运营商LT;<对于std :: string

时间:2013-08-12 07:31:47

标签: c++ operators

我定义了运算符<<对于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而不谈论字符串?即为什么它没有考虑我对运算符的定义&lt;&lt; ?

感谢。

更新。对于那些只能说“为什么要创建运算符&lt;&lt; for strings?”的人?并且无法说任何有用的东西:

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>'

1 个答案:

答案 0 :(得分:4)

工作:

#include <iostream>
#include <string>

std::string & operator<< (std::string & left, std::string & right){
    return left += right;
}

int main()
{
    std::string t1("t1"), t2("t2"), t3;
    t3 = t2 << t1;

    std::cout << t3;
}

Output: t2t1 [GCC 4.8.1]

正如您自己所说,编译器输出表明您的操作员重载甚至不可见。您不得在正确的地方声明您的声明。

无论如何,这不是一个好主意:你只会把任何阅读你代码的人混淆。 字符串不是流。