设计立方体类(Cube)
作者:互联网
题目描述
设计立方体类(Cube),求出立方体的面积和体积,分别用全局函数和成员函数判断两个立方体是否相等。(两个立方体相等当且仅当长宽高都相等。)
法一:利用成员函数判断
#include<iostream>
using namespace std;
class Cube {
public:
void setLong(int length) {
c_L = length;
}//可写,设置长
int getLong() {
return c_L;
}//可读,读取长
void setWidth(int width) {
c_W = width;
}//可写,设置长
int getWidth() {
return c_W;
}//可读,读取长
void setHeight(int height) {
c_H = height;
}//可写,设置长
int getHeight() {
return c_H;
}//可读,读取长
int calculateS() {
return 2 * c_L * c_W + 2 * c_L * c_H + 2 * c_W * c_H;
}//获取立方体表面积
int calculateV() {
return c_L * c_W * c_H;
}//获取立方体体积
bool isSameByClass(Cube& c) {
if ((c_L == c.getLong()) &&( c_W == c.getWidth()) && (c_H == c.getHeight())) {
return true;
}
return false;
}//利用成员函数判断二者是否相等
private:
int c_L;//长
int c_W;//宽
int c_H;//高
}C1,C2;
int main() {
int L1, W1, H1, L2, W2, H2;
cin >> L1 >> W1 >> H1;
cin >> L2 >> W2 >> H2;
C1.setLong(L1);
C1.setWidth(W1);
C1.setHeight(H1);
C2.setLong(L2);
C2.setWidth(W2);
C2.setHeight(H2);
cout << "C1的表面积是" << C1.calculateS() << endl;
cout << "C2的表面积是" << C2.calculateS() << endl;
cout << "C1的体积是" << C1.calculateV() << endl;
cout << "C2的体积是" << C2.calculateV() << endl;
if (C1.isSameByClass(C2))
cout << "根据成员函数判断,C1和C2是相等的。";
else
cout<< "根据成员函数判断,C1和C2是不等的。";
return 0;
}
法二:利用全局函数判断
#include<iostream>
using namespace std;
class Cube {
public:
void setLong(int length) {
c_L = length;
}//可写,设置长
int getLong() {
return c_L;
}//可读,读取长
void setWidth(int width) {
c_W = width;
}//可写,设置长
int getWidth() {
return c_W;
}//可读,读取长
void setHeight(int height) {
c_H = height;
}//可写,设置长
int getHeight() {
return c_H;
}//可读,读取长
int calculateS() {
return 2 * c_L * c_W + 2 * c_L * c_H + 2 * c_W * c_H;
}//获取立方体表面积
int calculateV() {
return c_L * c_W * c_H;
}//获取立方体体积
private:
int c_L;//长
int c_W;//宽
int c_H;//高
}C1,C2;
bool isSame(Cube& c1, Cube& c2) {
if ((c1.getLong() == c2.getLong()) && (c1.getWidth() == c2.getWidth()) && (c1.getHeight() == c2.getHeight()))
return true;
return false;
}
int main() {
int L1, W1, H1, L2, W2, H2;
cin >> L1 >> W1 >> H1;
cin >> L2 >> W2 >> H2;
C1.setLong(L1);
C1.setWidth(W1);
C1.setHeight(H1);
C2.setLong(L2);
C2.setWidth(W2);
C2.setHeight(H2);
cout << "C1的表面积是" << C1.calculateS() << endl;
cout << "C2的表面积是" << C2.calculateS() << endl;
cout << "C1的体积是" << C1.calculateV() << endl;
cout << "C2的体积是" << C2.calculateV() << endl;
if (isSame(C1,C2))
cout << "根据全局函数判断,C1和C2是相等的。";
else
cout << "根据全局函数判断,C1和C2是不等的。";
return 0;
}
标签:Cube,return,int,C2,立方体,设计,C1 来源: https://blog.csdn.net/Hyx1273724818/article/details/120579623