C++对象做成员变量(无师自通)
发布时间:2020-12-16 07:38:18 所属栏目:百科 来源:网络整理
导读:有时将一个类的对象嵌套在另一个类中是很有用的。例如,来看以下声明: class Rectangle{ private: double length; double width; public: void setLength(double); void setWidth(double); double getLength(); double getWidth(); double getArea();};class
有时将一个类的对象嵌套在另一个类中是很有用的。例如,来看以下声明:
class Rectangle { private: double length; double width; public: void setLength(double); void setWidth(double); double getLength(); double getWidth(); double getArea(); }; class Carpet { private: double pricePerSqYd; Rectangle size; // size 是 Rectangle 类的实例 public: void setPricePerYd(double p); void setDimensions(double l,double w); double getTotalPrice(); };请注意,Carpet 类有一个名为 size 的成员变量,它是 Rectangle 类的一个实例。Carpet 类可以使用此对象来存储房间尺寸并计算购买地毯的面积。图 1 说明了两个类是如何相关的。当一个类被嵌套在另一个类中时,称为对象组合。 ![]() 图 1 对象组合 下面的程序使用了这两个类来创建计算地毯销售价格: #include <iostream> using namespace std; class Rectangle { private: double length; double width; public: void setLength(double len) { length = len; } void setWidth(double wid) { width = wid; } double getLength() { return length; } double getWidth() { return width; } double getArea() { return length * width; } }; class Carpet { private: double pricePerSqYd; Rectangle size; public: void setPricePerYd(double p) { pricePerSqYd = p; } void setDimensions(double len,double wid) { size.setLength(len/3); // Convert feet to yards size.setWidth (wid/3); } double getTotalPrice() { return (size.getArea() * pricePerSqYd); } }; int main() { Carpet purchase; double pricePerYd; double length; double width; cout << "Room length in feet: "; cin >> length; cout << "Room width in feet : "; cin >> width; cout << "Carpet price per sq.yard: "; cin >> pricePerYd; purchase.setDimensions(length,width); purchase.setPricePerYd(pricePerYd); cout << "nThe total price of my new " << length << " x " << width << " carpet is $" << purchase.getTotalPrice() << endl; return 0; }程序运行结果:
Room length in feet: 16.5 另外值得注意的是,在第 43、44 和 48 行中,Carpet 类函数如何调用 Rectangle 函数。正如用户程序通过 Carpet 对象的名称调用 Carpet 函数一样,Carpet 类函数必须通过其 Rectangle 对象的名称调用 Rectangle 函数。在第 35 行中定义的 Rectangle 对象被命名为 size,这就是为什么 Carpet 函数使用以下语句来调用它: size.getArea() (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |