有的操作符重载函数只能是友元函数

1 基本概念

 

运算符重载为成员函数,第一个参数必须是本类的对象。而<<和>>的第一个操作数一定是ostream类型,所以<<只能重载为友元函数。

 


(1) 只能为友元

>>         ( 输入流操作 )
<<         ( 输出流操作 )

 

 

 

 

2 实例

 

(1)代码

#include
using namespace std;

class Test
{
    friend ostream & operator<<( ostream &out, Test &obj );
    friend istream & operator>>( istream &in, Test &obj );
    
public:
    Test( int a = 0, int b = 0 )
    {
        this->a = a;
        this->b = b;
    }

private:
    int a;
    int b;
};

ostream& operator<<( ostream &out, Test &obj )
{
    out << obj.a << " " << obj.b;
    return out;
}

istream& operator>>( istream &in, Test &obj )
{
    in >> obj.a >> obj.b;
    
    return in;
}

int main()
{
    Test t1( 1, 2 );
    cout << t1 << endl;
    
    cout << "input int:";
    cin >> t1;
    cout << t1 << endl;;
    return 0;
}

 

 

 

(2)输出

# ./operator 
1 2
input int:3 4
3 4

 

 

 

 

 

 

 

 

 

 

你可能感兴趣的:(C++,操作符重载)