面对对象的编程之赋值构造函数(f1=f2)

 

#include<iostream>
#include<Windows.h>
#include<string>

using namespace std;

#define ADDR_LEN 64

class Cat
{
public:
    Cat();
    Cat(const Cat &other);
    string getName();
    int getAge();
    void setAddr(char*addr);
    void description();

    //运算符重载函数
    Cat &operator=(const Cat &other);


private:
    string name;
    int age;
    char*addr;

};

string Cat::getName()
{
    return name;
}

int Cat::getAge()
{
    return age;
}
void Cat::setAddr(char*addr)
{
    if (!addr)
    {
        return;
    }
    strcpy_s(this->addr, ADDR_LEN, addr);
}

void Cat::description()
{
    cout << "姓名:" << name << "  年龄: " << age << "    地址: " << addr << endl;
}

Cat::Cat()
{
    cout << "调用手动默认构造函数" << endl;
    name = "小狸花";
    age = 14;
    addr = new char[ADDR_LEN];
    strcpy_s(addr, ADDR_LEN, "小狸花");

}

Cat::Cat(const Cat &other)
{
    cout << "调用拷贝构造函数" << endl;
    name = other.name;
    age = other.age;
    addr = new char[ADDR_LEN];
    strcpy_s(addr, ADDR_LEN, other.addr);
}

Cat & Cat::operator=(const Cat &other)
{
    //防止对象给自己赋值f1 =f1;
    if (this ==&other)
    {
        return *this;
    }
    //比如执行:f1=f2
    //就会调用:f1.operator=(f2);
    name = other.name;
    age = other.age;

    //如果有必要,需要先释放自己的资源(动态内存)
    delete addr;
    addr = new char[ADDR_LEN];
    //深拷贝
    strcpy_s(addr, ADDR_LEN, other.addr);

    //返回对象本身的引用,以便为了方便做链式处理;f1=f2=f3
    return *this;

}

int main()
{
    Cat h1,h2;
    h2 = h1; //自动调用赋值构造函数!位拷贝(浅拷贝)
    h1.description();
    h2.description();

    h1.setAddr((char*)"特朗普");
    cout << "改名字之后----------------------" << endl;
    h1.description();
    h2.description();
    

    system("pause");
    return 0;
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值