&1.参数使用引用是为了增加效率,因为如果不是引用,参数为对象则会调用拷贝构造函数
2.函数具有返回值是为了,若有连等赋值,保证其正常赋值
3.判断语句是为了保证不会出现自己给自己赋值的情况
4.返回值为引用是为了提升效率
赋值函数表面看起来只是对象赋值给对象,实际上是=号前的对象调用operator=方法,赋值函数的参数即为
=号后的对象
void main()
{
ST t(10,20);
ST t1;
t1 = t; //这里原理应该是 t1.operator=(&t)
}
//Test1.h
#include<iostream>
using namespace std;
class ST
{
private:
int a;
double b;
public:
ST(int a=0,double b=0):a(a),b(b)
{
this->a = a;
this->b = b;
cout<<"Object was built. "<<this<<endl;
}
ST(const ST &t);//拷贝构造
ST& operator=(const ST &t);
~ST()
{
cout<<"Object was free. "<<this<<endl;
}
};
ST::ST(const ST &t)
{
this->a = t.a;
this->b = t.b;
cout<<"Object was copy. "<<this<<endl;
}
//在类外实现方法时: 返回值 类名 ::函数名(参数)
ST& ST::operator=(const ST &t)
{
if(this != &t)
{
this->a = t.a;
this->b = t.b;
}
return *this;
}
#include<iostream>
#include"Test1.h"
using namespace std;
void main()
{
ST t(10,20);
ST t1;
t1 = t;
}
运行结果

原文:https://www.cnblogs.com/area-h-p/p/10325403.html