+ -
当前位置:首页 → 问答吧 → 关于运算符重载时 返回值的问题

关于运算符重载时 返回值的问题

时间:2011-12-15

来源:互联网

#include<iostream>
using namespace std;
class num
{
public:
  num()
  {
  n=99;
  cout<<"creat0"<<endl;
  }
  num(int i)
  {
  n=i;
  cout<<"creat1"<<endl;
  }
  ~num()
  {cout<<"destroyed"<<endl;}
  num(num&a)
  {
  n=a.n;
  cout<<"copy"<<endl;
  }
  int get() const{return n;}
  void set(int x){n=x;}
  const num operator+(const num&r)
  {
  return num(r.get()+n);
   
  }
  num &operator++()
  {
  ++n;
  return *this;
  }
  num operator++(int)
  {
  num temp(*this);
  ++n;
  return temp;
  }
num operator=(num &r) //重载"="运算符 并返回一个num类对象
{
return this->n=r.get(); //这里我认为是返回了n 可是编译还是过了 不理解原理 望解释
}
   
private:
  int n;
};


int main()
{
  num one(1),two(2),three;
  three=two;
  cout<<one.get()<<endl;
  cout<<two.get()<<endl;
  cout<<three.get()<<endl;
  return 0;
}

作者: a310394543   发布时间: 2011-12-15

还有就是在第二行注释处 单补调试的时候 发现又创建了一个num类对象~~~

有什么必要? 为什么不直接把参数r.get()取得的值赋给this->n?

作者: a310394543   发布时间: 2011-12-15

C/C++ code

num operator=(num &r) //重载"="运算符 并返回一个num类对象
{
    n=r.get(); 
    return *this;//返回类型是num类,所以要return *this;
}

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

num operator=(num &r) //重载"="运算符 并返回一个num类对象
{
this->n=r.get(); //这里我认为是返回了n 可是编译还是过了 不理解原理 望解释
return *this;//返回值是num类型,而不是this->n的类型
}

作者: mingliang1212   发布时间: 2011-12-15

num operator=(num &r) //重载"="运算符 并返回一个num类对象
{
return this->n=r.get(); //这里我认为是返回了n 可是编译还是过了 不理解原理 望解释
}
-------------------------------------
因为你自定义了从int到num的转换构造函数,且没有用explicity修饰,n被隐式转换为了num。

作者: supermegaboy   发布时间: 2011-12-15

引用 1 楼 a310394543 的回复:
还有就是在第二行注释处 单补调试的时候 发现又创建了一个num类对象~~~

有什么必要? 为什么不直接把参数r.get()取得的值赋给this->n?


原因与四楼一样。

作者: supermegaboy   发布时间: 2011-12-15

编译肯定是能过的,这里three=two;
这是你的赋值函数
num operator=(num &r) //重载"="运算符 并返回一个num类对象
{
return this->n=r.get(); //这里我认为是返回了n 可是编译还是过了 不理解原理 望解释
}
这里你返回值是n,函数的返回类型是num,这里他有临时变量生成的,自动由int类型的n转换到num类型的一个临时变量
然后本来要发生临时变量的拷贝的,编译器优化了

作者: qscool1987   发布时间: 2011-12-15