#include "iostream"
using namespace std;
class CA{
public:
int l;
int j;
public:
CA(){
cout<<"hello"<<endl;
l = 1;
j = 2;
}
CA(int a, int b){
cout<<"world"<<endl;
l = a;
j = b;
}
//拷贝构造函数,copy的原因是l = b.l,也有默认的
CA(CA& b)//参数引用,避免复制对象的过程
{
cout<<"拷贝构造函数"<<endl;
l = b.l;
j = b.j;
}
//A: 操作符重载实现为类成员函数
//重载的操作符在类体中被声明,声明方式如同普通成员函数一样,只不过他的名字包含关键字operator,以及紧跟其后的一个c++预定义的操作符。
/** //重载操作符right---------const CA& operator中的&可以省略
const CA& operator=(const CA& p) //const表示只能p改变this,不能反过来
{
cout<<"重载操作符 = "<<endl;
this->l = p.l;
this->j = p.j;
return *this; //没有返回值也没错--姚刚说默认返回this
}
*/
void display(){
cout<<"l="<<l<<endl;
cout<<"j="<<j<<endl;
}
};
//B:操作符重载实现为非类成员函数(全局函数)
//对于全局重载操作符,代表左操作数的参数必须被显式指定。
CA operator+(CA& p1, CA& p2) //const表示只能p改变this,不能反过来
{
cout<<"重载操作符 + "<<endl;
CA temp(p2.l + p1.l, p2.j + p1.j);
/**CA temp;
temp.l = l + p1.l;
temp.j = j + p1.j;*/
return temp; //调用拷贝构造函数
}
int main(){
CA a1(1,2);
CA a2(3,4);
CA a3;
a3 = a1+a2;
a3.display();
return 0;
}
using namespace std;
class CA{
public:
int l;
int j;
public:
CA(){
cout<<"hello"<<endl;
l = 1;
j = 2;
}
CA(int a, int b){
cout<<"world"<<endl;
l = a;
j = b;
}
//拷贝构造函数,copy的原因是l = b.l,也有默认的
CA(CA& b)//参数引用,避免复制对象的过程
{
cout<<"拷贝构造函数"<<endl;
l = b.l;
j = b.j;
}
//A: 操作符重载实现为类成员函数
//重载的操作符在类体中被声明,声明方式如同普通成员函数一样,只不过他的名字包含关键字operator,以及紧跟其后的一个c++预定义的操作符。
/** //重载操作符right---------const CA& operator中的&可以省略
const CA& operator=(const CA& p) //const表示只能p改变this,不能反过来
{
cout<<"重载操作符 = "<<endl;
this->l = p.l;
this->j = p.j;
return *this; //没有返回值也没错--姚刚说默认返回this
}
*/
void display(){
cout<<"l="<<l<<endl;
cout<<"j="<<j<<endl;
}
};
//B:操作符重载实现为非类成员函数(全局函数)
//对于全局重载操作符,代表左操作数的参数必须被显式指定。
CA operator+(CA& p1, CA& p2) //const表示只能p改变this,不能反过来
{
cout<<"重载操作符 + "<<endl;
CA temp(p2.l + p1.l, p2.j + p1.j);
/**CA temp;
temp.l = l + p1.l;
temp.j = j + p1.j;*/
return temp; //调用拷贝构造函数
}
int main(){
CA a1(1,2);
CA a2(3,4);
CA a3;
a3 = a1+a2;
a3.display();
return 0;
}