#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;
}
const CA operator+ (const CA& p1) //const表示只能p改变this,不能反过来
{
cout<<"重载操作符 + "<<endl;
CA temp(l + p1.l, j + p1.j);
/**CA temp;
temp.l = l + p1.l;
temp.j = j + p1.j;*/
return temp; //调用拷贝构造函数
}
//重载操作符right---------const CA& operator中的&可以省略
const CA operator=(const CA& p) //
{
cout<<"重载操作符 = "<<endl;
this->l = p.l;
this->j = p.j;
return *this; //没有返回值也没错--姚刚说默认返回this
}
//重载操作符right
/** const void operator=(const CA& p) //const表示只能p改变this,不能反过来 吗?
{
cout<<"重载操作符 = "<<endl;
this->l = p.l;
this->j = p.j;
} */
//error
/**const CA& operator=(const CA& p)
{
cout<<"重载操作符 = "<<endl;
return p; //等号失效,猜测是因为this没有改变。去掉const又报错
}//只得到一个引用函数---拷贝构造函数或许可以使用,但又有冲突
*/
};
int a=0;
void func(int &t)
{
a=t;
}
int main(){
CA a1(1,2);
CA* a2 = new CA(55,66);
CA a3; //hello
a3 = *a2; //重载操作符 =
cout<<a3.l<<endl;
cout<<a3.j<<endl;
//a3 + a1;
cout<<a3.l<<endl;
cout<<a3.j<<endl;
cout<<"begin"<<endl;
CA a4;
a4 = a1+a3;
//CA a4 = a1+a3;----error C2440: 'initializing' : cannot convert from 'const class CA' to 'class CA'
//No copy constructor available for class 'CA'??????????
cout<<"end"<<endl;
cout<<a4.l<<endl;
cout<<a4.j<<endl;
delete a2;
int t=3;
func(t);
cout<<a<<endl;//3---因为a只是一个值,a的内存空间不是t
t=4;
cout<<a<<endl;//3
CA a5 = a3; //拷贝构造函数
return 0;
}
C++重载运算符+,发现一些问题,暂未解决
最新推荐文章于 2022-01-18 16:49:09 发布