回 帖 发 新 帖 刷新版面

主题:[原创]这个前置运算符友元重载怎么不好使?

#include<iostream.h>
class Point
{
private:
    int x,y;
public:
    Point(int a,int b) {x=a,y=b;}
    void display()
    {    cout<<"("<<x<<","<<y<<")"<<endl;}
    friend Point operator ++(Point a);
};
Point operator ++(Point a)
{    return Point(9,9);}

void main()
{
    Point a(3,6);
    a.display();
    ++a;
    a.display();
}

////++a之后,a还是(3,6),这个前置重载根本没起作用,问下是哪里出了问题???

[em18][em18][em18][em18][em18]

回复列表 (共3个回复)

沙发

void main()
{
    Point a(3,6);
    a.display();
    [color=FF0000]++a;[/color]    // a = ++a;
    a.display();
}

根据你的『Point operator ++(Point a)』函数实现,上面方法可以显示<9,9>了

板凳

#include<iostream.h>
class Point
{
private:
    int x,y;
public:
    Point(int a,int b) {x=a,y=b;}
    void display()
    {    cout<<"("<<x<<","<<y<<")"<<endl;}
    void operator ++();
};
void Point::operator ++()
{
    x++;    // 也可以 x = 9
    y++;    // y = 9
}

void main()
{
    Point a(3,6);
    a.display();
    ++a;
    a.display();
}

3 楼


Point operator ++(Point a)
{    return Point(9,9);}

这个根本没将值赋给a,而且也没有声明的内存容纳Point(9, 9),而后面显示的还是a,所以a没变化。

修改如下:

[code=c]
#include<iostream.h>

class Point
{
private:
    int x, y;
public:
    Point(int a, int b):x(a), y(b) {}
    void display()
    {
        cout << "(" << x << "," << y << ")" << endl;
    }
    friend Point operator++(Point &a);
};

Point operator ++(Point &a)
{
    a.x++;
    a.y++;
    return a;
}

void main()
{
    Point a(3, 6);
    a.display();
    ++a;
    a.display();
}
[/code]

我来回复

您尚未登录,请登录后再回复。点此登录或注册