📄 assignoperator.cpp
字号:
// Listing 14.6
// Copy constructors
#include <iostream>
class CAT
{
public:
CAT(); // default constructor
// copy constructor and destructor elided!
int GetAge() const { return *itsAge; }
int GetWeight() const { return *itsWeight; }
void SetAge(int age) { *itsAge = age; }
CAT operator=(const CAT &);
private:
int *itsAge;
int *itsWeight;
};
CAT::CAT()
{
itsAge = new int;
itsWeight = new int;
*itsAge = 5;
*itsWeight = 9;
}
CAT CAT::operator=(const CAT & rhs)
{
if (this == &rhs)
return *this;
delete itsAge;
delete itsWeight;
itsAge = new int;
itsWeight = new int;
*itsAge = rhs.GetAge();
*itsWeight = rhs.GetWeight();
return *this;
}
int main()
{
CAT frisky;
std::cout << "frisky's age: " << frisky.GetAge()
<< std::endl;
std::cout << "Setting frisky to 6...\n";
frisky.SetAge(6);
CAT whiskers;
std::cout << "whiskers' age: " << whiskers.GetAge()
<< std::endl;
std::cout << "copying frisky to whiskers...\n";
whiskers = frisky;
std::cout << "whiskers' age: " << whiskers.GetAge()
<< std::endl;
return 0;
}
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -