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