.用c++代码,最起码是class,写一个复杂的程序,用放到类,继承与派生
时间: 2023-12-24 07:03:11 浏览: 75
好的,我可以给你一个例子,这个程序模拟了一个简单的银行系统,包含账户类、储蓄账户类和支票账户类,其中储蓄账户和支票账户都是从账户类派生而来。
```cpp
#include<iostream>
using namespace std;
//账户类
class Account {
protected:
string name;
long accountNumber;
double balance;
public:
Account(string name, long accountNumber, double balance) {
this->name = name;
this->accountNumber = accountNumber;
this->balance = balance;
}
virtual void display() {
cout << "Account: " << name << ", No: " << accountNumber << ", Balance: " << balance << endl;
}
virtual void withdraw(double amount) {
balance -= amount;
}
virtual void deposit(double amount) {
balance += amount;
}
};
//储蓄账户类
class SavingsAccount : public Account {
private:
double interestRate;
public:
SavingsAccount(string name, long accountNumber, double balance, double interestRate)
: Account(name, accountNumber, balance) {
this->interestRate = interestRate;
}
void display() {
cout << "Savings Account: " << name << ", No: " << accountNumber << ", Balance: " << balance << ", Interest Rate: " << interestRate << endl;
}
void addInterest() {
balance += balance * interestRate;
}
};
//支票账户类
class CheckingAccount : public Account {
private:
double overdraftLimit;
public:
CheckingAccount(string name, long accountNumber, double balance, double overdraftLimit)
: Account(name, accountNumber, balance) {
this->overdraftLimit = overdraftLimit;
}
void display() {
cout << "Checking Account: " << name << ", No: " << accountNumber << ", Balance: " << balance << ", Overdraft Limit: " << overdraftLimit << endl;
}
void withdraw(double amount) {
if (balance - amount >= -overdraftLimit) {
balance -= amount;
}
else {
cout << "Withdrawal amount exceeded overdraft limit." << endl;
}
}
};
int main() {
Account* account1 = new Account("Tom", 123456, 1000.0);
account1->display();
SavingsAccount* account2 = new SavingsAccount("Jerry", 789012, 2000.0, 0.01);
account2->display();
account2->addInterest();
CheckingAccount* account3 = new CheckingAccount("Spike", 345678, 3000.0, 2000.0);
account3->display();
account3->withdraw(4000.0);
delete account1;
delete account2;
delete account3;
return 0;
}
```
在这个程序中,我们定义了三个类:账户类(Account)、储蓄账户类(SavingsAccount)和支票账户类(CheckingAccount)。储蓄账户和支票账户都是从账户类派生而来,继承了账户类的属性和方法,并且增加了自己的属性和方法。
在主函数中,我们创建了一个账户对象、一个储蓄账户对象和一个支票账户对象,并通过指针调用各自的方法实现了存取款和计算利息等操作。最后,我们在程序结束时释放了各个对象的内存。
这个程序比较简单,但是涉及了面向对象编程的一些基本概念,例如类、继承、派生、多态等。希望对你有所帮助!
阅读全文