关于继承的困惑

Confusion regarding inheritance

本文关键字:继承 于继承      更新时间:2023-10-16

当我遇到这个问题时,我正在测试一个关于分层继承的小程序。该程序包含一个父类银行和两个子类提款和存款。

#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)Withdrawn 2)Depositn 3)Check Balancen 4)Display all detailsn 5)Exitn" << 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;

该程序没有任何缺陷。但是这样做违背了使用继承的全部目的。

我很困惑。为什么会这样?

类是对对象外观和行为的描述。你有三个。一个描述了你所说的bank,一个是deposit,一个是withdraw

对象是类的实例。因此,对象是具有类所说的存储和行为的东西。您有三个对象:bdw

每个对象都有自己独立的存储。如果你想让一个对象知道另一个对象,你需要告诉它。w不能只找到b.如果你有,比如说,b_barclaysb_natwestb_hsbc呢?您希望w找到哪个?为什么?

我认为您所做的是将告诉编译器如何创建对象的类与对象本身混为一谈。一个类继承自另一个类只是说子类将包括父类的行为和存储。所以它说,如果你创建两种类型的对象,那么子级将拥有父级能力的超集。它不会创建任何存储共享;每个都有完全独立的存储,按照类的定义进行布局。