C++ 类的成员函数

xwbar的头像
2025-06-23 20:26:59
/
世界杯克罗地亚

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

王者荣耀李元芳蔬乡物语价格介绍
陕西女首富周莹 周莹是清末陕西著名的女商人,被誉为“陕西女首富”“安吴寡妇”“清末女商圣”,其一生充满了传奇色彩。早年经历周莹出生于18...