简体   繁体   中英

Making an object belonging to a class depending on input parameters in C++

I'm trying to build an object which is of a type which depends on input parameters. Eg my object is called 'process' and at runtime an integer between 2 and 5 (inclusive) is entered and something a bit like this would happen:

if (input == 2) TwoJ   process;
if (input == 3) ThreeJ process;
if (input == 4) FourJ  process;
if (input == 5) FiveJ  process;

Obviously the above will not work because the object goes out of scope immediately. Is there a way to implement this nicely? Cheers

Use a factory function that returns a smart pointer to a base Process class and whose implementation is determined by an integer value supplied to the factory function (requires that all classes have a common base).

For example:

class Base_process
{
public:
    virtual ~Base_process() {}
    virtual void do_something() = 0;
};

class TwoJ : public Base_process
{
public:
    void do_something() {}
}
class ThreeJ : public Base_process
{
public:
    void do_something() {}
}

std::unique_ptr<Base_process> make_process(int a_type)
{
    if (a_type == 1) return std::unique_ptr<Base_process>(new TwoJ());
    if (a_type == 2) return std::unique_ptr<Base_process>(new ThreeJ());

    // Report invalid type or return an acceptable default if one exists.
    throw std::invalid_argument("Unknown type:" + std::to_string(a_type));
}

A factory method of sorts

std::unique_ptr<ProcessType> CreateProcess(int input){ 
    if(input == 2) return std::unique_ptr<ProcessType>(new TwoJ());
    .....
}

This assumes, of course, that the various classes you use have a common base class, here ProcessType , and that you are satisfied with interacting with it via a base class pointer.

you can but, you need 1 base class for those all eg

Base* process;

if (input == 2) process = new TwoJ();
if (input == 3) process = new ThreeJ();

then to access those class all you need is:

if (input == 2) (TwoJ*)process->someTwoJMethod();

or by using dynamic_cast:

TwoJ* p = dynamic_cast<TwoJ*>(process);
if(p != 0) {
   p->someTwoJMethod();
}

with this you own responsibility to delete your object once it's go out of scope. The previous answers are the best way in cpp using std::unique_ptr the object will get deleted automatically when the object go out of scope.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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