如何查找哪个类对象位于数组的特定索引上(多态性)
How to find which class object is sitting on a particular index of an array (Polymorphism )
我有一个银行的基类,它被"储蓄"、"支票"、"流动"和"投资"类继承。我正在为我的学校练习多态性。
我有一个很长的代码,我不能在这里分享。我在这段代码中所做的只是在指针 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...
相关文章:
- 数组索引的值没有增加
- 并行用于C++17中数组索引范围内的循环
- 数组索引重载错误
- 通过指针与数组引用扩展数组索引序列
- SIGSEGV, 分段错误. 而 printf() 数组索引的值
- 缓冲区溢出 - 数组索引越界(严重)
- 为什么C++数组索引值是有符号的,而不是围绕size_t类型构建的(或者我错了)
- 查找下一个具有真值C++的数组索引
- 在编译时自动生成用于稀疏数组索引的switch语句
- 在数组索引上引发异常
- C++ 将二维数组索引与条件语句中的函数值进行比较
- 平衡数组索引,同时从左和右对数组求和
- 为什么C ,Devstudio,数组索引工作
- 如何对同一数组索引下的结构成员进行排序?
- 我想返回数组索引,而不是数组值
- C++相当于 Python 的:用于数组索引
- 分段错误:为什么这里的数组索引越界了
- 数组索引在地图上不是整数
- 根据用户输入的每个字母添加到数组索引
- C 数组索引