+ -
当前位置:首页 → 问答吧 → 急急急!!快考试了!!哪位大虾帮帮忙!! c++运算符重载

急急急!!快考试了!!哪位大虾帮帮忙!! c++运算符重载

时间:2011-12-25

来源:互联网

#include<iostream>
using namespace std;
class A
{
private:
  int a,b,c;
public:
  A(int x,int y,int z);
  //void show();
  A operator+ (A plus);
};



#include"head.h"
A::A(int x,int y,int z)
{
  a=x;
  b=y;
  c=z;
}
A A::operator+(A plus)//当输完A::A后提示中并没有operator+ 这个函数 且这个函数编译不通过
{
  A u;
  u.a=plus.a+a;
  u.b=plus.b+b;
  u.c=plus.c+c;
  return u;
}

作者: nhlbengbeng   发布时间: 2011-12-25

C/C++ code

#include<iostream>
using namespace std;
class A
{
private:
  int a,b,c;
public:
  A(int x,int y,int z);
  //void show();
  A &A::operator+(A &plus);
};



//#include"head.h"
A::A(int x,int y,int z)
{
  a=x;
  b=y;
  c=z;
}
A &A::operator+(A &plus)//不能返回一个临时变量
{
    a=a+plus.a;
    b=b+plus.b;
    c=c+plus.c;
    return *this;
}

作者: shenxinji   发布时间: 2011-12-25

这样改试试:
C/C++ code
#include <iostream>

using namespace std;

class A
{
private:
  int a,b,c;
public:
  A(int x,int y,int z);
  A operator+(const A& plus);//定义为成员运算符
};

A::A(int x,int y,int z)
{
  a=x;
  b=y;
  c=z;
}

A A::operator+(const A& plus)
{
  this->a+=plus.a;
  this->b+=plus.b;
  this->c+=plus.c;
  return *this;
}

int main()
{
    return 0;
}

作者: nuaazdh   发布时间: 2011-12-25

噢...是可以返回临时对象的,我搞错了...不好意思

作者: shenxinji   发布时间: 2011-12-25

C/C++ code

#include<iostream>
using namespace std;
class A
{
private:
    int a,b,c;
public:
    A(){}
    A(int x,int y,int z);
    A operator+ (A plus);
    void show();
};

A::A(int x,int y,int z)
{
    a=x;
    b=y;
    c=z;
}
A A::operator+(A plus)
{
    A u;
    u.a=plus.a+a;
    u.b=plus.b+b;
    u.c=plus.c+c;
    return u;
}

void A::show()
{
    cout<<"a = "<<a<<endl;
    cout<<"b = "<<b<<endl;
    cout<<"c = "<<c<<endl;
}

int main()
{
    A t(1, 2, 3), te(1, 1, 1);
    t = t + te;
    t.show();
    return 0;
}

作者: udbwcso   发布时间: 2011-12-25