大佬教程收集整理的这篇文章主要介绍了C++对象做成员变量(无师自通),大佬教程大佬觉得挺不错的,现在分享给大家,也给大家做个参考。
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 get@R_262_10586@lPrice(); };请注意,Carpet 类有一个名为 size 的成员变量,它是 Rectangle 类的一个实例。Carpet 类可以使用此对象来存储房间尺寸并计算购买地毯的面积。图 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 get@R_262_10586@lPrice() { 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 @R_262_10586@l price of my new " << length << " x " << width << " carpet is $" << purchase.get@R_262_10586@lPrice() << endl; return 0; }程序运行结果:
Room length in feet: 16.5
Room width in feet : 12
Carpet price per sq.yard: 22,49
The @R_262_10586@l price of my new 16.5 x 12 carpet is $494.78
size.getArea()
以上是大佬教程为你收集整理的C++对象做成员变量(无师自通)全部内容,希望文章能够帮你解决C++对象做成员变量(无师自通)所遇到的程序开发问题。
如果觉得大佬教程网站内容还不错,欢迎将大佬教程推荐给程序员好友。
本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。