C-类与对象的实际应用案例详解
目录
C++ 类与对象的实际应用案例详解
在 C++ 面向对象编程中,类与对象的设计直接影响代码的可维护性和扩展性。以下通过三个典型案例,展示如何将类与对象应用于实际场景。
一、游戏角色管理系统
1. 需求分析
设计一个简单的游戏角色类,包含属性(生命值、攻击力)和行为(攻击、升级),并支持角色之间的战斗。
2. 类设计
#include <iostream>
#include <string>
class GameCharacter {
private:
std::string name;
int health;
int attackPower;
int level;
public:
// 构造函数
GameCharacter(std::string n, int h = 100, int ap = 10)
: name(n), health(h), attackPower(ap), level(1) {}
// 成员函数
void attack(GameCharacter& target) {
std::cout << name << " 攻击 " << target.name << ",造成 " << attackPower << " 伤害!" << std::endl;
target.health -= attackPower;
if (target.health <= 0) {
std::cout << target.name << " 被击败!" << std::endl;
}
}
void levelUp() {
level++;
health += 20;
attackPower += 5;
std::cout << name << " 升级到 Lv." << level << "!" << std::endl;
}
bool isAlive() const {
return health > 0;
}
// 显示状态
void displayStatus() const {
std::cout << "角色:" << name << " | 等级:" << level
<< " | 生命值:" << health << " | 攻击力:" << attackPower << std::endl;
}
};
3. 实际应用
int main() {
GameCharacter warrior("狂战", 150, 15);
GameCharacter mage("魔导", 80, 25);
warrior.displayStatus();
mage.displayStatus();
// 战斗流程
while (warrior.isAlive() && mage.isAlive()) {
warrior.attack(mage);
if (mage.isAlive()) {
mage.attack(warrior);
}
}
// 升级系统
if (warrior.isAlive()) {
warrior.levelUp();
warrior.displayStatus();
}
return 0;
}
4. 代码亮点
- 封装性
:通过
private
成员隐藏内部状态,仅通过公共方法操作。 - 继承扩展性
:可派生出
Warrior
、Mage
等子类,添加职业专属技能。
二、银行账户管理系统
1. 需求分析
设计一个银行账户类,支持存款、取款、查询余额,确保资金安全。
2. 类设计
#include <iostream>
#include <string>
#include <vector>
class BankAccount {
private:
std::string accountNumber;
std::string ownerName;
double balance;
std::vector<double> transactionHistory;
void recordTransaction(double amount) {
transactionHistory.push_back(amount);
}
public:
BankAccount(std::string accNo, std::string name, double initialBalance)
: accountNumber(accNo), ownerName(name), balance(initialBalance) {
if (initialBalance > 0) {
recordTransaction(initialBalance);
}
}
bool deposit(double amount) {
if (amount > 0) {
balance += amount;
recordTransaction(amount);
return true;
}
return false;
}
bool withdraw(double amount) {
if (amount > 0 && amount <= balance) {
balance -= amount;
recordTransaction(-amount);
return true;
}
return false;
}
void displayStatement() const {
std::cout << "账户流水(存入为正,支出为负):" << std::endl;
for (double t : transactionHistory) {
std::cout << t << " ";
}
std::cout << "\n当前余额: " << balance << std::endl;
}
};
3. 实际应用
int main() {
BankAccount account("123456", "张三", 1000.0);
account.deposit(500.0);
account.withdraw(300.0);
account.displayStatement();
return 0;
}
4. 代码亮点
- 事务记录
:通过
vector
保存交易历史,增强系统可追溯性。 - 异常处理 :在存款/取款时检查金额有效性,防止非法操作。
三、图形几何计算系统
1. 需求分析
设计一个图形基类,派生出圆形、矩形、三角形,实现面积和周长计算。
2. 类设计
#include <iostream>
#include <cmath>
class Shape {
public:
virtual double area() const = 0; // 纯虚函数(抽象类)
virtual double perimeter() const = 0;
virtual void displayInfo() const = 0;
};
class Circle : public Shape {
private:
double radius;
public:
Circle(double r) : radius(r) {}
double area() const override {
return M_PI * radius * radius;
}
double perimeter() const override {
return 2 * M_PI * radius;
}
void displayInfo() const override {
std::cout << "圆形:半径 = " << radius << std::endl;
}
};
class Rectangle : public Shape {
private:
double width, height;
public:
Rectangle(double w, double h) : width(w), height(h) {}
double area() const override {
return width * height;
}
double perimeter() const override {
return 2 * (width + height);
}
void displayInfo() const override {
std::cout << "矩形:宽 = " << width << ", 高 = " << height << std::endl;
}
};
3. 实际应用
int main() {
Shape* shapes[] = {
new Circle(5.0),
new Rectangle(4.0, 6.0)
};
for (auto shape : shapes) {
shape->displayInfo();
std::cout << "面积:" << shape->area()
<< ",周长:" << shape->perimeter() << std::endl;
delete shape;
}
return 0;
}
4. 代码亮点
- 多态性 :通过虚函数实现统一接口,不同图形类实现各自计算逻辑。
- 扩展性 :新增图形类型(如三角形)时,只需派生新类并实现纯虚函数。
四、总结与设计原则
1. 案例共同点
- 单一职责原则
:每个类专注于特定功能(如
GameCharacter
负责战斗逻辑)。 - 开闭原则 :通过继承扩展功能,而不修改原有代码(如添加新图形类型)。
2. 实际开发建议
- 优先组合而非继承
:如果类之间是“有一个”关系(如
BankAccount
包含交易记录),应使用成员对象而非继承。 - 合理使用访问控制
:将敏感数据设为
private
,提供public
接口进行操作。 - 利用抽象类 :通过纯虚函数定义接口规范,强制派生类实现必要功能。
通过这些案例可以看出,类与对象的设计需要结合具体业务场景,在灵活性和复杂性之间找到平衡。建议读者尝试实现一个完整的小型系统(如学生管理系统),进一步巩固面向对象编程能力。