提问者:小点点

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


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

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

例如,使用在Bank[0]创建了一个类型为“Savings”的对象。 当user添加完所有帐户后,我怎样才能在代码中找到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);
    }

共1个答案

匿名用户

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

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...