4elist1015.cpp
来自「《21天学通C++》附盘的原代码。书上的每个例子在这里都有相应的C语言程序。」· C++ 代码 · 共 55 行
CPP
55 行
// Listing 10.15
// Copy constructors
#include <iostream>
using namespace std;
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;
*itsAge = rhs.GetAge();
*itsWeight = rhs.GetWeight();
return *this;
}
int main()
{
CAT frisky;
cout << "frisky's age: " << frisky.GetAge() << endl;
cout << "Setting frisky to 6...\n";
frisky.SetAge(6);
CAT whiskers;
cout << "whiskers' age: " << whiskers.GetAge() << endl;
cout << "copying frisky to whiskers...\n";
whiskers = frisky;
cout << "whiskers' age: " << whiskers.GetAge() << endl;
return 0;
}
⌨️ 快捷键说明
复制代码Ctrl + C
搜索代码Ctrl + F
全屏模式F11
增大字号Ctrl + =
减小字号Ctrl + -
显示快捷键?