访问权限的基本介绍
C++中的访问权限分为三种:public、private和protected,用于控制类成员的可访问性。
| 访问权限 | 类内部 | 同一个类的对象 | 派生类(子类) | 类外部 |
|---|---|---|---|---|
| public | ✔ | ✔ | ✔ | ✔ |
| private | ✔ | ❌ | ❌ | ❌ |
| protected | ✔ | ❌ | ✔ | ❌ |
使用权限的优缺点
优点
- 封装性:隐藏内部实现,提高安全性和健壮性。
- 接口与实现分离:用户仅需关注公开接口,无需了解内部实现。
- 易于维护:修改内部实现不影响外部代码。
- 控制读写访问:精确控制成员的读写权限。
- 继承灵活性 :
protected成员在派生类中可访问。
缺点
- 增加复杂性:不当使用可能导致代码结构复杂化。
- 测试难度:私有成员无法直接测试。
- 灵活性降低:过于严格的封装可能限制有效用法。
- 可能导致紧耦合 :过度依赖
friend会增加类间耦合。
关键结论
public:类似C语言结构体,默认不写权限时为private。protected:在继承中发挥作用。private:强制通过公有方法操作数据,确保数据完整性。
示例:BankAccount类
通过私有成员保护余额,仅允许通过公有方法修改:
cpp
#include <iostream>
#include <string>
using namespace std;
/*
银行的账户是一个模板,是一个类,有存款人信息和账户额度,而具体的存款人视为一个对象,
一个对象不能私自修改账户额度,需要通过一个操作流程,比如去ATM或者柜台进行操作才能修改到账户额度,
所以,存款人信息和账户额度设计成私有权限,通过公有的操作流程,也就是公有函数去操作私有变量。
基于这个场景,我们编程实现代码
*/
class BankAccount {
private:
string name;
string addr;
int age;
double balance;
public:
string bankAddr;
void registerMes(string newName, string newAddr, int newAge, double newBalance);
void withdraw(double amount);
void deposit(double amount);
double getBalance();
void printUserInfo();
};
void BankAccount::printUserInfo() {
string mesTem = "账户名:" + name + ",地址:" + addr +
", 年龄:" + to_string(age) + ", 存款:" + to_string(balance);
cout << mesTem << endl;
}
void BankAccount::registerMes(string newName, string newAddr, int newAge, double newBalance) {
name = newName;
addr = newAddr;
age = newAge;
balance = newBalance;
}
void BankAccount::deposit(double amount) {
if (amount > 0) {
balance += amount;
} else {
cerr << "Deposit amount must be positive." << endl;
}
}
void BankAccount::withdraw(double amount) {
if (amount > balance) {
cerr << "Insufficient funds." << endl;
} else if (amount <= 0) {
cerr << "Withdrawal amount must be positive." << endl;
} else {
balance -= amount;
}
}
double BankAccount::getBalance() {
return balance;
}
int main() {
BankAccount user1;
user1.registerMes("sakura", "朝阳区", 35, 100);
user1.deposit(50);
user1.withdraw(30);
user1.printUserInfo();
return 0;
}
设计说明
- 私有成员 :
balance等数据无法直接外部修改,必须通过deposit、withdraw等公有方法。 - 封装性:防止非法操作(如负余额),确保数据完整性。
- 公有接口:提供清晰的操作方式,隐藏内部实现细节。