0

1.使用带有重载运算符 + 的
复制构造函数时出错 2.当从代码中删除复制构造函数时它工作正常

#include <iostream>
#include <cstdlib>
#include <ctime>


using namespace std;
class number {
  int n,p;
  public:
  number () {
     n= random ();
    p = random()+random();
    cout << "constructor with random called"<< endl;
}
number (int n1, int p1) {
    n =n1;
    p=p1;
    cout << "Constructor with value called"<< endl;
    cout << "n ="<< n<< endl;
    cout << "p = " << p<< endl;
}
int random () {
    srand (time(0));
int tmp =rand()%100;
return (tmp);
}
number operator +(number &obj1) ;
friend ostream& operator << (ostream &out,number &obj) ;
number (number &obj) {
     n= obj.n; 
      p=obj.p;
  }
} ;
 number number::operator+(number &obj1) {
    int tmp1 = n+obj1.n ;
     int tmp2 = p+obj1.p;
     return number (tmp1,tmp2);
}

int main(int argc, char **argv)
{   number n1;
number n2;
cout<< n1<< endl;
cout<< n1<< endl;
//cout << n1+n2<< endl;
return 0;
}

1)在使用带有重载运算符的复制构造函数时出现错误+
2)当从代码中删除复制构造函数时它工作正常

4

1 回答 1

2

您的复制构造函数采用左值,而默认生成的构造函数采用右值。

更改您的构造函数:

number (const number &obj)
//      ^^^^^

但我认为没有理由在这里使用用户定义的复制构造函数。

于 2013-10-20T08:38:29.263 回答