c++初学,计算立方体的体积和面积,并比较两个立方体是否相同:
#define _CRT_SECURE_NO_WARNINGS
#include<iostream>
using namespace std;
class cube
{
public:
int cubeS()
{
return 2*(w* l + w * h + l * h);
}
int cubeV()
{
return (w * l * h);
}
//成员函数实现比较c1和c2
bool cmpCube(cube &cub)
{
bool ret = w == cub.get_w() && l == cub.get_l() && h == cub.get_h();
return ret;
}
void set_w(int s_w)
{
w = s_w;
}
void set_l(int s_l)
{
l = s_l;
}
void set_h(int s_h)
{
h = s_h;
}
int get_w()
{
return w;
}
int get_l()
{
return l;
}
int get_h()
{
return h;
}
private:
int w;
int l;
int h;
};
//全局函数实现比较c1和c2
bool cmp_cube(cube &c1,cube &c2)
{
bool ret = c1.get_w() == c2.get_w() && c1.get_l() == c2.get_l() && c1.get_h() == c2.get_h();
return ret;
}
void test()
{
cube c1;
c1.set_l(5);
c1.set_h(3);
c1.set_w(8);
cube c2;
c2.set_l(5);
c2.set_h(3);
c2.set_w(8);
cout << "c1面积为:" << c1.cubeS() << " 体积为" <<c1.cubeV()<< endl;
cout << "c2面积为:" << c2.cubeS() << " 体积为" <<c2.cubeV()<< endl;
bool ret = c1.cmpCube(c2);
if (ret)
{
cout << "c1和c2相等" << endl;
}
else
{
cout << "c1和c2不相等" << endl;
}
ret = cmp_cube(c1,c2);
if (ret)
{
cout << "c1和c2相等" << endl;
}
else
{
cout << "c1和c2不相等" << endl;
}
}
int main()
{
test();
system("pause");
return EXIT_SUCCESS;
}