注册 登录
编程论坛 C++教室

帮忙看看问题出在哪里 关于运算符重载

lindayanglong 发布于 2008-09-02 15:11, 804 次点击
#include<iostream>
using namespace std;
class Point
{
    int x,y;
public:
    void set(int a,int b)
    {
        x=a;y=b;
    }
    void print() const
    {
        cout<<"x="<<x<<' '<<"y="<<y<<endl;
    }
    friend  Point operator+(const Point& a,const Point& b);
    friend   Point add(const Point& a, const Point& b);

};
  Point add(const Point& a, const Point& b)
{
    Point s;
    s.set(a.x+b.x,a.y+b.y);
    return s;
}
 Point operator +(const Point& a,const Point& b)
{
    Point s;
    s.set(a.x+b.x,a.y+b.y);
    return s;
}
int main()
{
    Point a,b;
    a.set(3,2);
    b.set(1,5);
    (a+b).print();
    operator+(a,b).print();
    add(a,b).print();

}
7 回复
#2
sunkaidong2008-09-02 15:35
我运行了下,结果没什么问题,但是涉及返回局部变量问题
#3
sunkaidong2008-09-02 15:36
operator+(a,b).print();一般也不这样用吧
#4
lindayanglong2008-09-02 18:21
我怎么会出现这样的运行错误啊?
Compiling...
a3.cpp
E:\vc++实验\a3\a3.cpp(15) : fatal error C1001: INTERNAL COMPILER ERROR
        (compiler file 'msc1.cpp', line 1786)
         Please choose the Technical Support command on the Visual C++
         Help menu, or open the Technical Support help file for more information
Error executing cl.exe.

a3.obj - 1 error(s), 0 warning(s)
#5
zzt_4282008-09-02 21:22
回复
返回局部对象是可以的,,只不过返回局部对象的指针或引用是不可以的.
#6
sunkaidong2008-09-02 22:39
可以分析下你的观点吗?
#7
sunkaidong2008-09-02 22:43
用vs2005没什么问题,我说错了一点,就是上面返回局部变量其实是涉及拷贝问题。。。如果数据过大,会浪费时间

[[it] 本帖最后由 sunkaidong 于 2008-9-2 22:51 编辑 [/it]]
#8
PcrazyC2008-09-02 22:59
这里没有涉及返回引用的问题,这个主要是你用的编译器不支持友元造成的.换个编译器吧,估计楼主用的VC 6.0,用VS2005,VS2008,DEV_C++都行,推荐后两个
1