C++ 类成员函数
类的成员函数(或称方法)是指那些把定义和原型写在类定义内部的函数,就像类定义中的其他变量一样。
类成员函数是类的一个成员,它默认已经传进了全部类成员。
让我们看看之前定义的类 Box,现在我们要使用成员函数来访问类的成员,而不是直接访问这些类的成员:
class box
{
public:
double length; // 长度
double breadth; // 宽度
double height; // 高度
double getVolume(void)
};
box::double getVolume(void)
{
return length * breadth * height;
}
//类中想要操作类中数据成元必须要用方法
//且成员函数只能在内部声明,外部定义
:: 叫作用域区分符,指明一个函数属于哪个类或一个数据属于哪个类,用在声明函数之后的解释函数。
调用成员函数是在对象上使用点运算符(.),这样它就能操作与该对象相关的数据和函数
常用到的方法:
让我们使用上面提到的概念来设置和获取类中不同的成员的值:
#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( )
{
Box Box1; // 声明 Box1,类型为 Box
Box Box2; // 声明 Box2,类型为 Box
double volume = 0.0; // 用于存储体积
// box 1 详述
Box1.setLength(6.0);
Box1.setBreadth(7.0);
Box1.setHeight(5.0);
// box 2 详述
Box2.setLength(12.0);
Box2.setBreadth(13.0);
Box2.setHeight(10.0);
// box 1 的体积
volume = Box1.getVolume();
cout << "Box1 的体积:" << volume <<endl;
// box 2 的体积
volume = Box2.getVolume();
cout << "Box2 的体积:" << volume <<endl;
return 0;
}
当上面的代码被编译和执行时,它会产生下列结果:
Box1 的体积: 210
Box2 的体积: 1560