hour14_1.cpp
来自「《24学时精通c++》的随书源码的下半部分。欢迎下载学习。」· C++ 代码 · 共 72 行
CPP
72 行
// 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 &);
bool 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;
}
bool CAT::operator==(const CAT & rhs)
{
int tempAge = *itsAge;
if (tempAge == rhs.GetAge()) return true;
else return false;
}
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;
if (firsky == whiskers) std::cout "Ages match \n";
else std::cout << "ages differ\n";
return 0;
}
⌨️ 快捷键说明
复制代码Ctrl + C
搜索代码Ctrl + F
全屏模式F11
增大字号Ctrl + =
减小字号Ctrl + -
显示快捷键?