-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