如何查找哪个类对象位于数组的特定索引上(多态性)

How to find which class object is sitting on a particular index of an array (Polymorphism )

本文关键字:数组 索引 于数组 多态性 对象 查找 何查找      更新时间:2023-10-16

我有一个银行的基类,它被"储蓄"、"支票"、"流动"和"投资"类继承。我正在为我的学校练习多态性。

我有一个很长的代码,我不能在这里分享。我在这段代码中所做的只是在指针 this->bank 处分配动态数组(我有单独的函数,grow2D(,并通过询问用户是否要创建"保存"、"检查"、"当前"或"投资"帐户的对象在运行时创建对象。我的问题是,在我通过询问用户创建完对象后,我如何检查对象的哪种类型("保存"、"检查"、"当前"或"投资"(位于特定索引上。

例如,使用 在银行 [0] 创建一个类型为"储蓄"的对象。当用户完成添加所有帐户后,如何在代码中稍后找到 bank[0] 上所在的对象类型?

string name;
unsigned long long int accountNumber;
unsigned long int balance;
int option = 0;
size++;
this->bank = grow2D(bank, size);
cout <<endl << "1 for Saving" << endl;
cout << "2 for Checking" << endl;
cout << "3 for Current" << endl;
cout << "4 for Investment" << endl;
cout << "Enter option";
cin >> option;
cin.ignore();
cout << "Enter name";
getline(cin, name);
cout << "Enter Account Number";
cin >> accountNumber;
cout << "Enter Balance";
cin >> balance;
if(option==1)
{
int interestRate;
cout << "Enter Interest Rate: ";
cin >> interestRate;
bank[size - 1] = new Saving(name,accountNumber,balance,interestRate);
}
else if (option == 2)
{
int fee;
cout << "Enter Fee: ";
cin >> fee;
bank[size - 1] = new Checking(name, accountNumber, balance,fee);
}
else if (option == 3)
{
int fee;
unsigned long int minimumBalance;
cout << "Enter Fee: ";
cin >> fee;
cout << "Enter Minimum balance: ";
cin >> minimumBalance;
bank[size - 1] = new Current(name, accountNumber, balance,fee,minimumBalance);
}
else if (option == 4)
{
int fee;
unsigned long int minimumBalance;
int profit;
cout << "Enter Fee: ";
cin >> fee;
cout << "Enter Minimum balance: ";
cin >> minimumBalance;
cout << "Enter Profit: ";
cin >> profit;
bank[size - 1] = new Investment(name, accountNumber, balance, fee, minimumBalance,profit);
}

假设你的类至少包含一个虚拟方法(至少析构函数应该是虚拟的(,例如:

class Saving {
public:
virtual ~Saving() = default;
};
class Checking: public Saving {};
class Current: public Saving {};
class Investment: public Saving {};

然后,您可以使用typeid()查询对象的运行时类型.
示例:

#include <typeinfo>
Saving* s = new Current();
if(typeid(*s) == typeid(Current)) {
std::cout << "It's a Current!" << std::endl;
}
if(typeid(*s) == typeid(Investment)) {
std::cout << "It's an Investment!" << std::endl;
}

或者,也可以使用dynamic_cast()并检查强制转换是否成功转换为派生类型:

Saving* s = new Investment();
Investment* investment = dynamic_cast<Investment*>(s);
if(investment != nullptr) {
std::cout << "It's an Investment!" << std::endl;
}
Current* current = dynamic_cast<Current*>(s);
if(current != nullptr) {
std::cout << "It's a Current!" << std::endl;
}
// etc...