C++面向物件入門--簡單的實現立方體類
阿新 • • 發佈:2020-08-09
#include <iostream> using namespace std; class Cube { //屬性 private: //長 double length; //高 double height; //寬 double width; //行為 public: //設定長 void setLength(double length) { this->length = length; } //獲取長 double getLength() { returnlength; } //設定高 void setHeight(double height) { this->height = height; } //獲取高 double getHeight() { return height; } //設定寬 void setWidth(double width) { this->width = width; } //獲取寬 double getWidth() { return width; }/** * 計算表面積 * surface n.表面;外觀;表層;v.浮出水面;使成平面;adj.表面的 * surface/surfacial area 表面積 * @return */ double calculateSurfaceArea() { return length * (width + height) * 2 + width * height * 2; } /** * 計算立方體的體積 * volume n.體積;量;音量;adj.大量的 * @return */ doublecalculateVolume() { return length * width * height; } /** * 比較體積是否相等 * @param c 欲比較的立方體Cube物件 * @return 比較結果 */ bool equalsVolume(Cube& c) { return calculateVolume() == c.calculateVolume(); } }; bool equalsVolume(Cube& c1,Cube& c2) { return c1.calculateVolume() == c2.calculateVolume(); } int main() { Cube c1; c1.setLength(2.5); c1.setWidth(7.5); c1.setHeight(4); cout << "Cube c1's volume is " << c1.calculateVolume() << endl; cout << "Cube c1's surface area is " << c1.calculateSurfaceArea() << endl; Cube c2; c2.setLength(5); c2.setWidth(3); c2.setHeight(5); cout << "Is the volume of Cube c1 is equals to the volume of Cube c2 ?" << (c1.equalsVolume(c2) ? "yes" : "no") << endl; cout << "Is the volume of Cube c1 is equals to the volume of Cube c2 ?" << (equalsVolume(c1, c2) ? "yes" : "no") << endl; system("pause"); return 0; }