这段代码的关键在于了解成员函数和全局函数调用的区别
#include <iostream>
using namespace std;
class Cube{
public:
void setM_H(int h) {
m_H = h;
}
int getM_H(){
return m_H;
}
void setM_L(int l) {
m_L = l;
}
int getM_L() {
return m_L;
}
void setM_W(int w) {
m_W = w;
}
int getM_W() {
return m_W;
}
int calculateS() {
return 2 * m_H * m_L + 2 * m_H * m_W + 2 * m_L * m_W;
}
int calculateV() {
return m_H * m_L * m_W;
}
bool isSameByClass(Cube& c) {
if (m_H == c.getM_H() && m_L == c.getM_L() && m_W == c.getM_W()) {
return true;
}
else {
return false;
}
}
private:
int m_H;
int m_L;
int m_W;
};
//利用全局函数判断是否相等
bool isSame(Cube &c1, Cube &c2) {
if (c1.getM_H() == c2.getM_H() && c1.getM_L() == c2.getM_L() && c1.getM_W() == c2.getM_W()) {
return true;
}
else {
return false;
}
}
int main()
{
Cube c1;
c1.setM_H(10);
c1.setM_L(10);
c1.setM_W(10);
Cube c2;
c2.setM_H(10);
c2.setM_L(10);
c2.setM_W(10);
cout << c1.calculateS() << endl;
cout << c1.calculateV() << endl;
bool ret = isSame(c1, c2);
if (ret) {
cout << "true" << endl;
}
else {
cout << "false" << endl;
}
//利用成员函数判断是否相等
ret = c1.isSameByClass(c2);//用c1调用成员函数在成员函数内传入c2
if (ret) {
cout << "true" << endl;
}
else {
cout << "false" << endl;
}
system("pause");