![](https://csdnimg.cn/release/download_crawler_static/86891880/bg10.jpg)
16
可以,类的每一个对象都有自己的数据成员。
4-6 什么叫做拷贝构造函数?拷贝构造函数何时被调用?
解:
拷贝构造函数是一种特殊的构造函数,具有一般构造函数的所
有特性,其形参是本类的对象的引用,其作用是使用一个已经
存在的对象,去初始化一个新的同类的对象。在以下三种情况
下会被调用:在当用类的一个对象去初始化该类的另一个对象
时;如果函数的形参是类对象,调用函数进行形参和实参结合
时;如果函数的返回值是类对象,函数调用完成返回时;
4-7 拷贝构造函数与赋值运算符 (=) 有何不同?
解:
赋值运算符 (=) 作用于一个已存在的对象; 而拷贝构造函数会创
建一个新的对象。
4-8 定义一个 Dog 类,包含的 age、weight 等属性,以及对这
些属性操作的方法。实现并测试这个类。
解:
源程序:
#include <iostream.h>
class Dog
{
public:
Dog (int initialAge = 0 , int initialWeight = 5);
~Dog();
int GetAge() { return itsAge;} // inline!
void SetAge (int age) { itsAge = age;} // inline!
int GetWeight() { return itsWeight;} // inline!
void SetWeight (int weight) { itsAge = weight;} // inline!
private:
int itsAge , itsWeight;
};
Dog::Dog(int initialAge , int initialWeight)
{
itsAge = initialAge;
itsWeight = initialWeight;
}
Dog::~Dog() //destructor , takes no action
{
}
int main()
{
Dog Jack(2 , 10);
cout << "Jack is a Dog who is " ;
cout << Jack.GetAge() << " years old and";
cout << Jack.GetWeight() << " pounds weight.\n";
Jack.SetAge(7);
Jack.SetWeight(20);
cout << "Now Jack is " ;
cout << Jack.GetAge() << " years old and";
cout << Jack.GetWeight() << " pounds weight.";
return 0;
}
程序运行输出:
Jack is a Dog who is 2 years old and 10 pounds weight.
Now Jack is 7 years old 20 pounds weight.
4-9 设计并测试一个名为 Rectangle 的矩形类,其属性为矩形
的左下角与右上角两个点的坐标,能计算矩形的面积。
解:
源程序:
#include <iostream.h>
class Rectangle
{
public:
Rectangle (int top, int left, int bottom, int right);
~Rectangle () {}
int GetTop() const { return itsTop; }
int GetLeft() const { return itsLeft; }
int GetBottom() const { return itsBottom; }
int GetRight() const { return itsRight; }
void SetTop(int top) { itsTop = top; }
void SetLeft (int left) { itsLeft = left; }
void SetBottom (int bottom) { itsBottom = bottom; }
void SetRight (int right) { itsRight = right; }
int GetArea() const;