aiguo者 2016-01-05 11:57 采纳率: 25%
浏览 1555
已采纳

c++中运算符重载 这个小程序怎么不对呢

#include
using namespace std;

class R{
public :
int n;
int d;

R(int a,int b)
{
    this->n=a;
    this->d=b;
}

};

ostream operator<< (ostream &os,R &r)
{
// os<<r.n<<endl;
// os<<r.d<<endl;;

os<<r.n<<','<<r.d;
return os; //此处报错了 在vs2015中做的
}

int main()
{

R a(2,3),b(4,5);
cout<<a<<b;
return 0;

}

  • 写回答

3条回答 默认 最新

  • 任飘萍 2016-01-07 08:51
    关注

    这是我写的一个重载输入输出去处符的小例子, 你参考一下吧

    class Test

    {
    public:
        int a;
        int b;
        Test():a(0),b(0){}
        Test(int a, int b):a(a),b(b){}
        //重载输入输出运算符,只能用友元函数
        friend ostream &operator<<(ostream &os, const Test &T);
        friend istream &operator>>(istream &is, Test &T);
    };
    
    ostream &operator<<(ostream &os, const Test &T)
    {
        os << "a = " << T.a << endl;
        os << "b = " << T.b << endl;
    
        return os;
    }
    
    istream &operator>>(istream &is, Test &T)
    {
        is >> T.a >> T.b;
        return is;
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?