[英]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: 例如,我的对象称为“进程”,并且在运行时输入2到5之间的一个整数(含2和5)(包括整数),并且会发生如下情况:
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). 使用工厂函数 ,该函数将智能指针返回到基本Process
类,并且其实现由提供给该工厂函数的整数值确定(要求所有类都具有公共基数)。
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. 当然,这假定您使用的各种类都有一个公共的基类,这里为ProcessType
,并且您对通过基类指针与其进行交互感到满意。
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: 或使用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. 前面的答案是使用std::unique_ptr
的cpp中的最佳方法,当对象超出范围时,该对象将被自动删除。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.