有关C++的拷贝构造函数

重新复习一遍C++的

constructor, construct with arguments, copy constructor, copy assignment

下面重点要强调的是有关copy constructor,constructor ,和 copy assignment。

如果拷贝参数是对象的话,注意要使用常引用即 const &。 如果返回值是对象的话,返回的也是该对象的引用。


#include "iostream"
#include "string"

class CTime{
        std::string *ptr;
    public:
        //default constructor
        CTime(){}
        //constructor with one parameter
        CTime(const std::string &str):ptr(new std::string(str)){}
        //Copy constructor
        CTime(const CTime &x):ptr(new std::string(x.getContent())){}
        //copy assignment
        CTime& operator =(const CTime& x){
            delete ptr;
            ptr = new std::string(x.getContent());
            return *this;
        }
        //destructor
        ~CTime(){
            delete ptr;
        }
        //get content
        const std::string& getContent() const{
            return *ptr;
        }
};

int main(){
    CTime Timea("this is 11 o\'clolck ");
    CTime Timeb("24");
    CTime Timec(Timea);
    Timeb = Timea;
    std::cout << Timea.getContent() << std::endl;
    std::cout << Timeb.getContent() << std::endl;
    std::cout << Timec.getContent() << std::endl;
    return 0;
}


  




评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值