C++ 成员函数
C++成员函数[编辑 | 编辑源代码]
成员函数(Member Functions)是C++面向对象编程中的核心概念之一,它定义了类的行为,允许对象执行特定操作或访问其内部数据。成员函数可以是普通成员函数、静态成员函数、常量成员函数或友元函数等。本文将详细介绍C++成员函数的定义、使用方式及实际应用场景。
基本概念[编辑 | 编辑源代码]
成员函数是定义在类(或结构体)内部的函数,用于描述对象的行为。它们可以直接访问类的私有(private)、保护(protected)和公有(public)成员变量和其他成员函数。成员函数的声明通常在类定义内部,而实现可以在类内部或外部(使用作用域解析运算符`::`)。
成员函数的语法如下:
class ClassName {
public:
ReturnType functionName(Parameters); // 声明成员函数
};
ReturnType ClassName::functionName(Parameters) { // 定义成员函数(类外部)
// 函数体
}
成员函数的类型[编辑 | 编辑源代码]
C++中的成员函数可以分为以下几种类型:
1. 普通成员函数[编辑 | 编辑源代码]
普通成员函数属于类的实例,必须通过对象调用。它们可以访问类的所有成员(包括私有成员)。
示例:
#include <iostream>
using namespace std;
class Rectangle {
private:
int width, height;
public:
void setDimensions(int w, int h) { // 普通成员函数
width = w;
height = h;
}
int calculateArea() { // 普通成员函数
return width * height;
}
};
int main() {
Rectangle rect;
rect.setDimensions(5, 10);
cout << "Area: " << rect.calculateArea() << endl; // 输出: Area: 50
return 0;
}
2. 静态成员函数[编辑 | 编辑源代码]
静态成员函数属于类本身而非对象,可以直接通过类名调用。它们只能访问静态成员变量和其他静态成员函数。
示例:
#include <iostream>
using namespace std;
class MathUtility {
public:
static int square(int x) { // 静态成员函数
return x * x;
}
};
int main() {
cout << "Square of 4: " << MathUtility::square(4) << endl; // 输出: Square of 4: 16
return 0;
}
3. 常量成员函数[编辑 | 编辑源代码]
常量成员函数承诺不会修改对象的状态(即不会修改成员变量),在函数声明后加`const`关键字。
示例:
#include <iostream>
using namespace std;
class Circle {
private:
double radius;
public:
Circle(double r) : radius(r) {}
double getArea() const { // 常量成员函数
return 3.14159 * radius * radius;
}
};
int main() {
const Circle c(5.0); // 常量对象
cout << "Area: " << c.getArea() << endl; // 输出: Area: 78.5397
return 0;
}
4. 友元函数[编辑 | 编辑源代码]
友元函数不是成员函数,但可以访问类的私有成员。它们需要在类内部声明为`friend`。
示例:
#include <iostream>
using namespace std;
class Box {
private:
int volume;
public:
Box(int v) : volume(v) {}
friend void printVolume(const Box& b); // 友元函数声明
};
void printVolume(const Box& b) { // 友元函数定义
cout << "Volume: " << b.volume << endl;
}
int main() {
Box box(100);
printVolume(box); // 输出: Volume: 100
return 0;
}
成员函数的高级特性[编辑 | 编辑源代码]
内联成员函数[编辑 | 编辑源代码]
在类定义内部直接实现的成员函数默认为内联函数(inline),编译器可能会将其展开以减少函数调用开销。
示例:
class Calculator {
public:
int add(int a, int b) { return a + b; } // 内联成员函数
};
重载成员函数[编辑 | 编辑源代码]
成员函数可以重载(即同名函数,参数列表不同)。
示例:
#include <iostream>
using namespace std;
class Printer {
public:
void print(int i) { cout << "Integer: " << i << endl; }
void print(double d) { cout << "Double: " << d << endl; }
};
int main() {
Printer p;
p.print(5); // 输出: Integer: 5
p.print(3.14); // 输出: Double: 3.14
return 0;
}
虚函数与多态[编辑 | 编辑源代码]
虚函数(`virtual`)支持运行时多态,允许派生类重写基类的成员函数。
示例:
#include <iostream>
using namespace std;
class Shape {
public:
virtual void draw() { cout << "Drawing a shape." << endl; } // 虚函数
};
class Circle : public Shape {
public:
void draw() override { cout << "Drawing a circle." << endl; } // 重写虚函数
};
int main() {
Shape* shape = new Circle();
shape->draw(); // 输出: Drawing a circle.
delete shape;
return 0;
}
实际应用案例[编辑 | 编辑源代码]
以下是一个银行账户类的示例,展示成员函数在实际开发中的应用:
#include <iostream>
using namespace std;
class BankAccount {
private:
string owner;
double balance;
public:
BankAccount(string name, double initialBalance) : owner(name), balance(initialBalance) {}
void deposit(double amount) {
if (amount > 0) balance += amount;
}
bool withdraw(double amount) {
if (amount > 0 && balance >= amount) {
balance -= amount;
return true;
}
return false;
}
double getBalance() const { return balance; }
string getOwner() const { return owner; }
};
int main() {
BankAccount account("Alice", 1000.0);
account.deposit(500.0);
if (account.withdraw(200.0)) {
cout << account.getOwner() << "'s balance: $" << account.getBalance() << endl;
}
return 0;
}
总结[编辑 | 编辑源代码]
成员函数是C++面向对象编程的核心组成部分,它们定义了类的行为并封装了操作逻辑。通过合理使用普通成员函数、静态成员函数、常量成员函数和虚函数,可以构建灵活且高效的面向对象程序。
成员函数的设计应遵循以下原则:
- 高内聚:一个函数只完成一个明确的任务。
- 低耦合:减少函数对外部状态的依赖。
- 清晰的命名:函数名应准确描述其功能。