c15_09.cpp
来自「it can help you use C++ program we」· C++ 代码 · 共 66 行
CPP
66 行
// 重载赋值运算符=,重载函数中预防自复制的代码
#include <iostream >
#include <string>
using namespace std;
class CCat
{
public:
CCat(); //缺省构造函数
int GetAge() const { return *m_age; }
char *GetName() const { return m_name; }
void SetAge(int age) { *m_age = age; }
void SetName(char *name);
CCat operator=(const CCat &); //重载赋值运算符
private:
int *m_age;
char *m_name;
};
CCat::CCat()
{
m_age = new int; //给指针分配空间
*m_age = 5;
m_name = new char[20]; //给Name指针分配空间
strcpy(m_name, "Mypet");
}
void CCat::SetName(char *name)
{
delete []m_name;
m_name = new char[strlen(name)+1];
strcpy(m_name, name);
}
CCat CCat::operator=(const CCat & sCat)
{
//如果源对象的地址和this指针相等,说明它们是同一个对象,是自赋值
if (this == &sCat)
return *this;
delete []m_name; //删除原有的空间
m_name = new char[strlen(sCat.m_name)+1]; //分配新的存储空间
*m_age = sCat.GetAge();
strcpy(m_name, sCat.m_name); //将源对象的值赋给当前对象
return *this; //返回当前对象
}
int main()
{
CCat cat1;
cat1.SetAge(2);
cout<< "cat1的年龄是: "<<cat1.GetAge()<< endl
<< " 昵称:"<<cat1.GetName()<<endl;
CCat cat2;
cat2.SetName("SunFlower");
cout<< "cat2的年龄是: "<<cat2.GetAge()<< endl
<< " 昵称:"<<cat2.GetName()<<endl;
cout<< "\n把cat1的值赋给cat2...\n\n";
cat2 = cat1;
cout<< "cat2的年龄是: " << cat2.GetAge() << endl
<< " 昵称:"<<cat1.GetName()<<endl;
return 0;
}
⌨️ 快捷键说明
复制代码Ctrl + C
搜索代码Ctrl + F
全屏模式F11
增大字号Ctrl + =
减小字号Ctrl + -
显示快捷键?