C++中对operator=进行重写

/*************************************************************************
	> File Name: copy1.cpp
	> Author: 
	> Mail: 
	> Created Time: 2020年06月17日 星期三 15时36分57秒
 ************************************************************************/

#include<iostream>
using namespace std;

class Example{
    std::string* ptr;
    public:
    Example():ptr(new std::string){}//new std::string返回的值是存储字符串的地址
    Example(const std::string& str):ptr(new std::string(str)){}
    Example(const Example& example):ptr(new std::string(example.content())){};
    ~Example(){delete ptr;}
    const std::string& content()const{return *ptr;}
    Example& operator= (const Example& x){
        cout<<"执行了"<<endl;
        delete ptr;//释放指针指向的字符串占用的内存
        ptr = new string(x.content());
        return *this;
    }
    Example operator+(const Example & rhs){
        return Example(content()+rhs.content());
    }

    void print_information()const{
        cout<< *ptr<<endl;
    }
};

int main(){
    Example bar1("hello");
    bar1.print_information();
    Example bar2("world");
    bar2.print_information();
    Example bar3 = Example(bar1);
    bar3.print_information();
    Example bar4 = bar2;
    bar4.print_information();

    Example foo("Exam");
    Example ba = Example("ple");
    foo = foo + ba;
    cout<<"foo's content:"<<foo.content()<<endl;


    
    return 0;
}

编译执行
在这里插入图片描述

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值