c++ 成员函数
时间: 2025-05-24 17:02:11 浏览: 12
### C++ 成员函数的定义与用法
#### 1. 成员函数的定义方式
成员函数可以在类体内直接定义,这种情况下,默认会被视为 `inline` 函数[^4]。如果希望在类体外定义,则需要使用作用域解析运算符 (`::`) 明确指定该函数所属的类[^2]。
以下是两种常见的定义方式:
- **类内定义**
```cpp
class Box {
public:
double length;
double breadth;
double height;
// 类内定义的成员函数
double getVolume() {
return length * breadth * height;
}
};
```
- **类外定义**
```cpp
class Student {
public:
void display();
private:
int num;
std::string name;
char sex;
};
void Student::display() { // 使用作用域解析运算符定义成员函数
std::cout << "num:" << num << std::endl;
std::cout << "name:" << name << std::endl;
std::cout << "sex:" << sex << std::endl;
}
```
#### 2. 成员函数的属性
成员函数可以根据其访问权限分为三类:`private`、`protected` 和 `public`。这些修饰符决定了哪些外部代码能够调用它们[^5]。
#### 3. 成员函数的调用方式
成员函数可以通过以下几种方式进行调用:
- 如果是 `public` 的成员函数,可以直接通过对象实例调用。
- 可以通过指针调用成员函数,需借助箭头操作符 (`->`)[^5]。
- 在类内部,其他成员函数可以直接调用当前类中的成员函数[^5]。
示例代码如下:
```cpp
Student stud1;
stud1.display(); // 对象实例调用公有成员函数
Student* ptr = &stud1;
ptr->display(); // 指针调用成员函数
```
#### 4. 特殊特性——`this` 指针
当调用某个对象的成员函数时,编译器会自动将该对象的地址作为隐含参数传递给成员函数。这个隐含参数被称为 `this` 指针,它是一个常量指针,指向调用该成员函数的对象实例。
示例代码展示 `this` 指针的作用:
```cpp
class MyClass {
public:
int value;
void setValue(int v) {
this->value = v; // 使用 this 指向当前对象的数据成员
}
int getValue() const {
return value;
}
};
```
#### 5. 成员函数指针
C++ 支持定义指向成员函数的指针。这类指针的语法较为复杂,通常用于动态绑定场景下调用特定的成员函数[^3]。
示例代码如下:
```cpp
#include <iostream>
using namespace std;
class MyClass {
public:
void funcA() { cout << "Function A called." << endl; }
void funcB() { cout << "Function B called." << endl; }
};
int main() {
MyClass obj;
// 定义指向成员函数的指针
void (MyClass::*funcPtr)();
funcPtr = &MyClass::funcA; // 将 funcPtr 指向 funcA
(obj.*funcPtr)(); // 调用 funcA
funcPtr = &MyClass::funcB; // 将 funcPtr 指向 funcB
(obj.*funcPtr)(); // 调用 funcB
return 0;
}
```
---
阅读全文
相关推荐













