- C++ 基础
- C++ 首页
- C++ 概述
- C++ 环境设置
- C++ 基本语法
- C++ 注释
- C++ Hello World
- C++ 省略命名空间
- C++ 常量/字面量
- C++ 关键字
- C++ 标识符
- C++ 数据类型
- C++ 数值数据类型
- C++ 字符数据类型
- C++ 布尔数据类型
- C++ 变量类型
- C++ 变量作用域
- C++ 多个变量
- C++ 基本输入/输出
- C++ 修饰符类型
- C++ 存储类
- C++ 运算符
- C++ 数字
- C++ 枚举
- C++ 引用
- C++ 日期和时间
- C++ 控制语句
- C++ 决策制定
- C++ if 语句
- C++ if else 语句
- C++ 嵌套 if 语句
- C++ switch 语句
- C++ 嵌套 switch 语句
- C++ 循环类型
- C++ while 循环
- C++ for 循环
- C++ do while 循环
- C++ foreach 循环
- C++ 嵌套循环
- C++ break 语句
- C++ continue 语句
- C++ goto 语句
- C++ 构造函数
- C++ 构造函数和析构函数
- C++ 复制构造函数
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 <iostream>
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 <<endl;
// volume of box 2
volume = Box2.getVolume();
cout << "Volume of Box2 : " << volume <<endl;
return 0;
}
当以上代码编译并执行时,会产生以下结果:
Volume of Box1 : 210 Volume of Box2 : 1560
广告