天天看點

C++的重載流輸出運算符

// 下列代碼輸出什麼?

#include <iostream>

#include <string>

// typedef basic_ostream<char> ostream;

class A

{

private:

    int m1,m2;

public:

    A(int a, int b) {

        m1=a;m2=b;

    }

    operator std::string() const { return "str"; }

    operator int() const { return 2018; }

};

int main()

    A a(1,2);

    std::cout << a;

    return 0;

答案是2018,

因為類basic_ostream有成員函數operator<<(int),

而沒有成員函數operator<<(const std::string&),

優先調用同名的成員函數,故輸出2018,相關源代碼如下:

// 名字空間std中的全局函數

/usr/include/c++/4.8.2/bits/basic_string.h:

template<typename _CharT, typename _Traits, typename _Alloc>

inline basic_ostream<_CharT, _Traits>&

operator <<(basic_ostream<_CharT, _Traits>& __os,

            const basic_string<_CharT, _Traits, _Alloc>& __str)

    return __ostream_insert(__os, __str.data(), __str.size());

}

// 類basic_ostream的成員函數

//  std::cout為名字空間std中的類basic_ostream的一個執行個體

ostream:

__ostream_type& basic_ostream::operator<<(int __n);

// 下列代碼有什麼問題,如何修改?

    std::ostream& operator <<(std::ostream& os) {

        os << m1 << m2; return os;

類basic_ostream沒有成員函數“operator <<(const A&)”,

也不存在全局的:

operator <<(const basic_ostream&, const A&)

而隻有左操作數是自己時才會調用成員重載操作符,

都不符合,是以文法錯誤。

有兩種修改方式:

1) 将“std::cout << a”改成“a.operator <<(std::cout)”,

2) 或定義全局的:

std::ostream& operator<<(std::ostream& os, const A& a) {

    os << a.m1 << a.m2; return os;

繼續閱讀