简体   繁体   English

根据用户输入使用多态来调用函数

[英]Using Polymorphism to call a function depending on user input

I have an abstract class "Base" and derived classes such as Hexadecimal, Binary and so on... . 我有一个抽象类“ Base”和派生类,例如Hexadecimal,Binary等。 User enters a string telling me what base he is currently using and enters the number. 用户输入一个字符串,告诉我他当前正在使用什么基础,然后输入数字。 I need to use polymorphism (instead of control statements such as if, switch, etc...) to create the needed object or at least change that number to decimal so I can do the calculations needed with different numbers in different bases that I receive from user. 我需要使用多态性(而不是诸如if,switch等之类的控制语句)来创建所需的对象,或者至少将该数字更改为十进制,以便我可以使用收到的不同基数的不同数字进行所需的计算来自用户。 I tried a lot but cannot find out how to do this. 我尝试了很多,但找不到解决方法。 My current idea is to dynamically call "double toDec(const Base&)" function but don't think if it is the right move: 我目前的想法是动态调用“ double toDec(const Base&)”函数,但不认为这是正确的做法:

#include <iostream>
#include <string>
using namespace std;

class Base
{
public:
    Base(string n, string b) : number(n), base(b) {}
    virtual string whatBaseAreYou(string) = 0;
    virtual double toDec(const Base&) { whatBaseAreYou(base); }  
protected:
    string number;
    string base;
};

class Hex : public Base
{
public:
    virtual double toDec(const Base&);
};

class Binary : public Base
{
public:
    virtual double toDec(const Base&);
};

int main()
{
    string number,base;
    cin >> number >> base;
    Base* b = new Base(number,base); //I know this line is compile error.. I don't know how to implement this...
}

I can determine my current number's base, but how can I dynamically create for example a Binary class during run time? 我可以确定当前数字的基数,但是如何在运行时动态创建例如Binary类呢? I'm not even sure if I need abstract class Base... I don't know if I'm moving in the right direction here... this is a Inheritance + Polymorphism assignment that's why I need to solve it with these features. 我什至不确定我是否需要抽象类Base ...我不知道我是否在朝着正确的方向前进...这是一个Inheritance + Polymorphism作业,这就是为什么我需要使用这些功能来解决它。

I think you should look into factory method pattern. 我认为您应该研究工厂方法模式。 This will return you pointer to your base class and you will be able to call toDec method. 这将使您返回指向基类的指针,并且可以调用toDec方法。

Usually factory method will require you to use some switch statement but if you don't want to do this at all cost take a look at how to implement factory without using if or switches here: 通常工厂方法会要求您使用一些switch语句,但是如果您不愿意为此付出任何代价,请查看如何在不使用if或switch的情况下实现工厂:

https://stackoverflow.com/a/3502010/8855783 https://stackoverflow.com/a/3502010/8855783

This will only work if construcor of every of derived class (from Base) needs the same arguments 仅当每个派生类的构造函数(来自Base)需要相同的参数时,这才起作用

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM