数据抽象和数据封装是面向对象编程中的两个核心概念,它们可以帮助我们将程序中的数据和实现细节与外部隔离开来,提高程序的安全性和可维护性。
以下是一个C++代码示例,用于演示数据抽象和数据封装的概念:
#include
using namespace std;
class BankAccount {
private:
int accountNumber; // 账号
double balance; // 余额
public:
BankAccount(int accountNumber, double balance) {
this->accountNumber = accountNumber;
this->balance = balance;
}
void deposit(double amount) {
balance += amount;
}
void withdraw(double amount) {
if (balance >= amount) {
balance -= amount;
} else {
cout << "余额不足" << endl;
}
}
double getBalance() {
return balance;
}
};
int main() {
BankAccount myAccount(123456, 1000.0);
myAccount.deposit(500.0);
myAccount.withdraw(2000.0);
cout << "账户余额为:" << myAccount.getBalance() << endl;
return 0;
}
在上面的代码中,BankAccount类封装了账号和余额两个数据成员,同时提供了deposit()、withdraw()和getBalance()三个成员函数对账户进行操作。由于数据成员被声明为private,外部无法直接访问,从而实现了数据的安全性和完整性。同时,通过成员函数对数据进行操作,实现了数据抽象的概念。