c++++ 中的继承允许创建新类,从基类继承数据和函数;多态通过虚函数和基类指针实现,允许对象根据类型展示不同行为。实战案例展示了继承和多态在银行账户层次结构中的应用,包括储蓄、支票和信用卡账户,每个账户类型都有特定行为,例如存款、取款、支付账单等。
C++ 函数的艺术:继承与多态,对象设计模式之精髓
继承
继承是 C++ 中一种创建新类的方式,新类继承了基类的数据成员和成员函数。语法如下:
立即学习“C++免费学习笔记(深入)”;
class DerivedClass : public BaseClass { // Derived class members };
多态
多态是对象设计模式的核心,允许对象根据其类型表现出不同的行为。虚函数和基类指针是实现多态的关键。语法如下:
class BaseClass { public: virtual void doSomething() = 0; // 抽象函数 }; class DerivedClass : public BaseClass { public: void doSomething() override { // 覆盖基类函数 } };
实战案例:多态银行账户
创建一个银行账户层次结构,实现储蓄账户、支票账户和信用卡账户。
#include <iostream> class BankAccount { protected: double balance; public: virtual double getBalance() const { return balance; } }; class SavingsAccount : public BankAccount { public: void deposit(double amount) { balance += amount; } double withdraw(double amount) { if (amount <= balance) { balance -= amount; return balance; } return -1; // 提款失败 } }; class CheckingAccount : public BankAccount { public: void deposit(double amount) { balance += amount; } double withdraw(double amount) { if (amount <= balance) { balance -= amount; return amount; } return -1; // 提款失败 } bool payBill(double amount) { if (amount <= balance) { balance -= amount; return true; } return false; // 支付账单失败 } }; class CreditCardAccount : public BankAccount { protected: double creditLimit; public: CreditCardAccount(double limit) : creditLimit(limit) {} void deposit(double amount) { balance = amount; } double withdraw(double amount) { if (amount <= balance) { balance -= amount; return balance; } else if (balance + creditLimit >= amount) { double overdraft = amount - balance; balance = -overdraft; return amount; } return -1; // 提款失败 } }; void printBalance(BankAccount& account) { std::cout << "Balance: " << account.getBalance() << std::endl; } int main() { SavingsAccount savings; CheckingAccount checking; CreditCardAccount credit(1000); savings.deposit(500); savings.withdraw(200); printBalance(savings); checking.deposit(1000); checking.withdraw(800); checking.payBill(300); printBalance(checking); credit.deposit(200); credit.withdraw(500); printBalance(credit); return 0; }
在这个示例中,继承和多态被用于创建银行账户层次结构,其中每个账户类型都有不同的行为。调用基类函数 getBalance() 和 printBalance() 可以为所有账户类型一致地获取和打印余额。
以上就是C++ 函数的艺术:继承与多态,对象设计模式之精髄的详细内容,更多请关注本网内其它相关文章!