【发布时间】:2017-08-25 13:05:03
【问题描述】:
当我遇到这个问题时,我正在测试一个关于分层继承的小程序。该程序包含一个父类 Bank 和两个子类 Withdraw & Deposit。
#include<iostream>
#include<conio.h>
#include<stdlib.h>
//Hierarchical Inheritance
using namespace std;
class bank{
protected:
char name[20];
int age, id;
float bal;
public:
void getData(){
cout <<"Enter your name, age, bank ID and balance" << endl;
cin >> name >> age >> id >> bal;
}
void display(){
cout <<"Name: " << name << endl << "ID: " << id << endl;
cout <<"Age: " << age <<endl <<"Balance: " << bal << endl;
}
void check(){
cout <<"Your balance is " << bal << endl;
}
};
class withdraw : public bank{
float wd;
public:
void withdrawMoney(){
cout << "Enter the amount to withdraw" << endl;
cin >> wd;
if(wd > bal)
cout << "You cannot withdraw that much. Your balance is only " << bal << endl;
else{
bal = bal-wd;
cout << "You successfully withdrew " << wd << ". Your remaining balance is " << bal << endl;
}
}
};
class deposit : public bank{
float dp;
public:
void depo(){
cout <<"Enter the amount to deposit" << endl;
cin >> dp;
bal = bal+dp;
cout <<"You successfully deposited " << dp << ". Your balance is now " << bal << "." << endl;
}
};
int main()
{
int c;
bank b;
deposit d;
withdraw w;
b.getData();
do{
cout <<"***The Dank Bank***" << endl;
cout <<"What do you want to do?\n 1)Withdraw\n 2)Deposit\n 3)Check Balance\n 4)Display all details\n 5)Exit\n" << endl;
cin >> c;
if(c == 1)
w.withdrawMoney();
else if (c == 2)
d.depo();
else if(c == 3)
b.check();
else if(c == 4)
b.display();
else if(c == 5)
exit(0);
else
cout <<"Wrong choice." << endl;
cout<<"Press any key to continue" << endl;
getch();
}
while(1);
getch();
return 0;
}
执行提现功能时,我得到以下输出:
你不能撤回那么多。您的余额只有 6.03937e-039
使用存款功能时,输出显示存款金额而不是实际余额。
您已成功存入 1000。您的余额现在为 1000。
两个子类使用的唯一变量是 bal,所以我决定像这样全局声明它。
#include<iostream>
#include<conio.h>
#include<stdlib.h>
float bal;
程序运行没有任何缺陷。但是这样做违背了使用继承的全部目的。
我很困惑。为什么会这样?
【问题讨论】:
-
你的继承对我来说没有多大意义。如果是我,我会拥有一个有账户的银行。那么提款的存款将是 account 上的操作(即函数),而不是单独的类。简单提示:名词是类,动词是函数。
-
这是因为
withdrawal和deposit是bank的两个实例,有自己的bal -
您有 3 个不相关的变量
bank b; deposit d; withdraw w;。修改一个不会影响其他的。 -
并且除了已经提到的错误之外,类成员没有初始化,因此
bal在实例化时包含随机垃圾。您需要花更多时间阅读您的 C++ 书籍。 -
class withdraw : public bank等等...什么?
标签: c++ inheritance hierarchical