复制构造函数和返回临时对象的c ++冲突

时间:2015-08-28 09:32:05

标签: c++

  1 #include <iostream>
  2 #include <cmath>
  3 
  4 using namespace std;
  5 
  6 class complx
  7 {
  8 private:
  9     double real;
 10     double imag;
 11 public:
 12     complx() {}
 13     complx(double r, double i): real(r), imag(i) {}
 14     complx(complx &c) {real = c.real; imag = c.imag;}
 15     complx operator + (const complx &c) const
 16     {
 17         return complx(real + c.real, imag + c.imag);
 18     }
 19 
 20     complx & operator=(const complx & c)
 21     {
 22         real = c.real;
 23         imag = c.imag;
 24 
 25         return *this;
 26     }
 27 
 28     friend ostream& operator << (ostream &os, const complx &c);
 29 
 30     double size() const
 31     {
 32         return sqrt(real*real + imag*imag);
 33     }
 34 };
 35 
 36 ostream & operator << (ostream &os, const complx &c)
 37 {
 38     os << "(" << c.real << "," << c.imag << ")";
 39 
 40     return os;
 41 }
 42 
 43 const complx & maximum(const complx &c1, const complx &c2)
 44 {
 45     if (c1.size() > c2.size())
 46     {
 47         return c1;
 48     }
 49     else
 50     {
 51         return c2;
 52     }
 53 }
 54 
 55 
 56 int main(void)
 57 {
 58     complx c1(10, 30);
 59     complx c2(13, 25);
 60     complx mx = maximum(c1, c2);
 61 
 62     cout << c1 << endl;
 63     return 0;
 64 }

我不知道这段代码有什么问题,它无法通过编译。只有当我注释第14行(复制构造函数)或重写第17行以返回具体对象时,它才会通过编译并正确运行。

2 个答案:

答案 0 :(得分:2)

问题是var result = Array1 for(var i in Array2){ if(result[i]){ for(var p in Array2[i]){ result[i][p] = Array2[i][p] } } else {result[i] = Array2[i]} } 不会绑定到临时的。要修复,您应该将其重新定义为:

complx(complx &c)

还有一个建议:使用初始化列表,或者更好的是,将其他构造函数转发给从原始值构造的构造函数:

complx(const complx &c);

应该是:

complx(complx &c) {real = c.real; imag = c.imag;}

答案 1 :(得分:1)

复制构造函数应该使用const参数,以确保您不会在构造函数体内更改参数的属性,那么构造函数的签名应该是classname (const classname &obj)

相关问题