C++重载运算符+,发现一些问题,暂未解决

#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;
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值