Sams Teach Yourself C++ in 21 Days

(singke) #1
Working with Advanced Functions 319

10


14: void SetAge(int age) { *itsAge = age; }
15: Cat & operator=(const Cat &);
16:
17: private:
18: int *itsAge;
19: int *itsWeight;
20: };
21:
22: Cat::Cat()
23: {
24: itsAge = new int;
25: itsWeight = new int;
26: *itsAge = 5;
27: *itsWeight = 9;
28: }
29:
30:
31: Cat & Cat::operator=(const Cat & rhs)
32: {
33: if (this == &rhs)
34: return *this;
35: *itsAge = rhs.GetAge();
36: *itsWeight = rhs.GetWeight();
37: return *this;
38: }
39:
40:
41: int main()
42: {
43: Cat Frisky;
44: cout << “Frisky’s age: “ << Frisky.GetAge() << endl;
45: cout << “Setting Frisky to 6...\n”;
46: Frisky.SetAge(6);
47: Cat Whiskers;
48: cout << “Whiskers’ age: “ << Whiskers.GetAge() << endl;
49: cout << “copying Frisky to Whiskers...\n”;
50: Whiskers = Frisky;
51: cout << “Whiskers’ age: “ << Whiskers.GetAge() << endl;
52: return 0;
53: }

Frisky’s age: 5
Setting Frisky to 6...
Whiskers’ age: 5
copying Frisky to Whiskers...
Whiskers’ age: 6

OUTPUT


LISTING10.15 continued

Free download pdf