C++ 类成员函数
上一页
下一页
类的成员函数是指其定义或原型在类定义中像任何其他变量一样。它对属于其成员的类的任何对象进行操作,并且可以访问该对象类的所有成员。
让我们以之前定义的类为例,使用成员函数访问类的成员,而不是直接访问它们:
class Box {
public:
double length; // Length of a box
double breadth; // Breadth of a box
double height; // Height of a box
double getVolume(void);// Returns box volume
};
定义类成员函数
成员函数可以在类定义中定义,也可以使用作用域解析运算符 :单独定义。在类定义中定义成员函数会声明该函数为内联函数,即使您没有使用内联说明符。因此,您可以将Volume()函数定义如下:
在类内定义成员函数
class Box {
public:
double length; // Length of a box
double breadth; // Breadth of a box
double height; // Height of a box
double getVolume(void) {
return length * breadth * height;
}
};
在类外定义成员函数
如果您愿意,可以使用作用域解析运算符 (::)在类外定义相同的函数,如下所示:
double Box::getVolume(void) {
return length * breadth * height;
}
这里,唯一需要注意的是,您必须在 :: 运算符之前使用类名。
调用(访问)成员函数
成员函数将使用点运算符 (.)在对象上调用,它只操作与该对象相关的数据,如下所示:
Box myBox; // Create an object
myBox.getVolume(); // Call member function for the object
示例
让我们将上述概念应用于设置和获取类中不同类成员的值:
#include
using namespace std;
class Box {
public:
double length; // Length of a box
double breadth; // Breadth of a box
double height; // Height of a box
// Member functions declaration
double getVolume(void);
void setLength( double len );
void setBreadth( double bre );
void setHeight( double hei );
};
// Member functions definitions
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;
}
// Main function for the program
int main() {
Box Box1; // Declare Box1 of type Box
Box Box2; // Declare Box2 of type Box
double volume = 0.0; // Store the volume of a box here
// box 1 specification
Box1.setLength(6.0);
Box1.setBreadth(7.0);
Box1.setHeight(5.0);
// box 2 specification
Box2.setLength(12.0);
Box2.setBreadth(13.0);
Box2.setHeight(10.0);
// volume of box 1
volume = Box1.getVolume();
cout << "Volume of Box1 : " << volume < // volume of box 2 volume = Box2.getVolume(); cout << "Volume of Box2 : " << volume < return 0; } 当以上代码编译并执行时,会产生以下结果: Volume of Box1 : 210 Volume of Box2 : 1560 打印页面 上一页 下一页 广告