封装
1. 封装的概念
2. 封装的示例
#include <iostream>
class BankAccount {
private:
double balance; // 私有数据成员
public:
// 构造函数
BankAccount(double initial_balance) : balance(initial_balance) {}
// 公共方法:存款
void deposit(double amount) {
if (amount > 0) {
balance += amount; // 更新余额
std::cout << "Deposited: " << amount << std::endl;
} else {
std::cout << "Invalid deposit amount." << std::endl;
}
}
// 公共方法:取款
void withdraw(double amount) {
if (amount > 0 && amount <= balance) {
balance -= amount; // 更新余额
std::cout << "Withdrawn: " << amount << std::endl;
} else {
std::cout << "Invalid withdrawal amount." << std::endl;
}
}
// 公共方法:查询余额
void displayBalance() const {
std::cout << "Current balance: " << balance << std::endl;
}
};
int main() {
BankAccount account(1000.0); // 创建 BankAccount 对象
account.deposit(500.0); // 存款
account.withdraw(200.0); // 取款
account.displayBalance(); // 查询余额
// 尝试直接访问私有数据成员(编译错误)
// account.balance = 1500.0; // 这将导致编译错误
return 0;
}3. 封装的好处
4. 封装的注意事项
5. 总结
Last updated