C++ 类成员函数
#include <iostream>using namespace std;
// 类定义
class Box
{
public:
double length;
double breadth;
double height;
// 成员函数声明
double getVolume(void); // 返回体积
void setLength(double len);
void setBreadth(double bre);
void setHeight(double hei);
};
// 成员函数定义
double Box::getVolume(void)
{
return length * breadth * height;
}
void Box::setLength(double len)
{
length = len;
}
void Box::setBreadth(double bre)
{
breadth = bre;
}
void Box::setHeight(double hei)
{
height = hei;
}
// 主函数
int main()
{
// 创建对象Box1
Box Box1;
// 创建对象Box2
Box Box2;
double volume = 0.0;
// 调用成员函数
Box1.setLength(1.0);
Box1.setBreadth(2.0);
Box1.setHeight(3.0);
Box2.setLength(4.0);
Box2.setBreadth(5.0);
Box2.setHeight(6.0);
volume = Box1.getVolume();
cout << "Box1的体积:" << volume << endl;
volume = Box2.getVolume();
cout << "Box2的体积:" << volume << endl;
system("pause");
return 0;
}
页:
[1]