关于运算符重载时 返回值的问题
时间:2011-12-15
来源:互联网
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
有什么必要? 为什么不直接把参数r.get()取得的值赋给this->n?
作者: a310394543 发布时间: 2011-12-15
num operator=(num &r) //重载"="运算符 并返回一个num类对象 { n=r.get(); return *this;//返回类型是num类,所以要return *this; }
作者: shenxinji 发布时间: 2011-12-15
{
this->n=r.get(); //这里我认为是返回了n 可是编译还是过了 不理解原理 望解释
return *this;//返回值是num类型,而不是this->n的类型
}
作者: mingliang1212 发布时间: 2011-12-15
{
return this->n=r.get(); //这里我认为是返回了n 可是编译还是过了 不理解原理 望解释
}
-------------------------------------
因为你自定义了从int到num的转换构造函数,且没有用explicity修饰,n被隐式转换为了num。
作者: supermegaboy 发布时间: 2011-12-15
还有就是在第二行注释处 单补调试的时候 发现又创建了一个num类对象~~~
有什么必要? 为什么不直接把参数r.get()取得的值赋给this->n?
原因与四楼一样。
作者: supermegaboy 发布时间: 2011-12-15
这是你的赋值函数
num operator=(num &r) //重载"="运算符 并返回一个num类对象
{
return this->n=r.get(); //这里我认为是返回了n 可是编译还是过了 不理解原理 望解释
}
这里你返回值是n,函数的返回类型是num,这里他有临时变量生成的,自动由int类型的n转换到num类型的一个临时变量
然后本来要发生临时变量的拷贝的,编译器优化了
作者: qscool1987 发布时间: 2011-12-15
热门阅读
-
office 2019专业增强版最新2021版激活秘钥/序列号/激活码推荐 附激活工具
阅读:74
-
如何安装mysql8.0
阅读:31
-
Word快速设置标题样式步骤详解
阅读:28
-
20+道必知必会的Vue面试题(附答案解析)
阅读:37
-
HTML如何制作表单
阅读:22
-
百词斩可以改天数吗?当然可以,4个步骤轻松修改天数!
阅读:31
-
ET文件格式和XLS格式文件之间如何转化?
阅读:24
-
react和vue的区别及优缺点是什么
阅读:121
-
支付宝人脸识别如何关闭?
阅读:21
-
腾讯微云怎么修改照片或视频备份路径?
阅读:28