-4

我为 std::string 对象定义了 operator<<:

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 而不是谈论字符串?即为什么它不考虑我对 operator<< 的定义?

谢谢。

更新。对于那些只能说“为什么要为字符串创建 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>'
4

1 回答 1

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;
}

输出: t2t1 [GCC 4.8.1]

正如您自己所说,编译器输出表明您的运算符重载甚至不可见。你不能把你的声明放在正确的地方。

无论如何,这并不是一个好主意:您只会让任何阅读您的代码的人感到困惑。字符串不是流。

于 2013-08-12T07:37:07.043 回答