C++ 判断两个长方体是否相等—类的使用
作者:互联网
定义一个Cube类
计算表面积和体积,并判断长方体是否相等(分别用全局函数和成员函数来实现)。
参考代码:
#include <iostream>
using namespace std;
class Cube {
private:
double m_l;
double m_w;
double m_h;
public:
//设置长宽高
void setL(double l) {
m_l = l;
}
void setW(double w) {
m_w = w;
}
void setH(double h) {
m_h = h;
}
//获得长宽高
double getL() {
return m_l;
}
double getW() {
return m_w;
}
double getH() {
return m_h;
}
//计算面积
double getA() {
return (m_l * m_w + m_l * m_h + m_w * m_h) * 2;
}
//计算体积
double getV() {
return m_l * m_w * m_h;
}
//成员函数判断长方体是否相等
//长方体的长宽高顺序不一,需要重复判断
bool compareCube2(Cube &ob) {
if((m_l = ob.m_l) && (m_w == ob.m_w) && (m_h == ob.m_h)) {
return true;
} else if((m_l = ob.m_l) && (m_w == ob.m_h) && (m_h == ob.m_w)) {
return true;
} else if((m_l = ob.m_w) && (m_w == ob.m_l) && (m_h == ob.m_h)) {
return true;
} else if((m_l = ob.m_w) && (m_w == ob.m_h) && (m_h == ob.m_l)) {
return true;
} else if((m_l = ob.m_h) && (m_w == ob.m_w) && (m_h == ob.m_l)) {
return true;
} else if((m_l = ob.m_h) && (m_w == ob.m_l) && (m_h == ob.m_w)) {
return true;
} else {
return false;
}
}
};
//全局函数判断长方体是否相等
//长方体的长宽高顺序不一,需要重复判断
bool compareCube(Cube &cube1, Cube &cube2) {
if((cube1.getL() == cube2.getL()) && (cube1.getW() == cube2.getW()) \
&& (cube1.getH() == cube2.getH())) {
return true;
}
if((cube1.getL() == cube2.getL()) && (cube1.getW() == cube2.getH()) \
&& (cube1.getH() == cube2.getW())) {
return true;
}
if((cube1.getL() == cube2.getW()) && (cube1.getW() == cube2.getL()) \
&& (cube1.getH() == cube2.getH())) {
return true;
}
if((cube1.getL() == cube2.getW()) && (cube1.getW() == cube2.getH()) \
&& (cube1.getH() == cube2.getL())) {
return true;
}
if((cube1.getL() == cube2.getH()) && (cube1.getW() == cube2.getL()) \
&& (cube1.getH() == cube2.getW())) {
return true;
}
if((cube1.getL() == cube2.getH()) && (cube1.getW() == cube2.getW()) \
&& (cube1.getH() == cube2.getL())) {
return true;
}
return false;
}
void test() {
//长方体1
Cube cube1;
cube1.setL(2);
cube1.setW(1);
cube1.setH(3);
cout << "计算长方体1面积:" << cube1.getA() << endl;
cout << "计算长方体1体积:" << cube1.getV() << endl;
cout << "----------------" << endl;
//长方体2
Cube cube2;
cube2.setL(1);
cube2.setW(3);
cube2.setH(2);
cout << "计算长方体2面积:" << cube2.getA() << endl;
cout << "计算长方体2体积:" << cube2.getV() << endl;
cout << "----------------" << endl;
//长方体3
Cube cube3;
cube3.setL(1);
cube3.setW(2);
cube3.setH(5);
cout << "计算长方体3面积:" << cube3.getA() << endl;
cout << "计算长方体3体积:" << cube3.getV() << endl;
cout << "----------------" << endl;
//全局函数
cout << "长方体1 长方体2" << endl;
if(compareCube(cube1, cube2) == true) {
cout << "两个长方体相等" << endl;
} else {
cout << "两个长方体不相等" << endl;
}
cout << "----------------" << endl;
//成员函数
cout << "长方体1 长方体3" << endl;
if(cube3.compareCube2(cube1) == true) {
cout << "两个长方体相等" << endl;
} else {
cout << "两个长方体不相等" << endl;
}
}
int main() {
test();
return 0;
}
运行结果:
标签:getH,cube1,cube2,相等,return,ob,C++,&&,长方体 来源: https://blog.csdn.net/weixin_45981481/article/details/119254237