Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/cplusplus/135.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如何声明和定义在编译时返回少数未知自定义类之一的函数? C++中,我需要创建一个函数,它将返回一个对象,该对象将是不同可能类的实例,但在编译时我不知道它将是什么类(取决于用户行为)。_C++_Class_Oop - Fatal编程技术网

如何声明和定义在编译时返回少数未知自定义类之一的函数? C++中,我需要创建一个函数,它将返回一个对象,该对象将是不同可能类的实例,但在编译时我不知道它将是什么类(取决于用户行为)。

如何声明和定义在编译时返回少数未知自定义类之一的函数? C++中,我需要创建一个函数,它将返回一个对象,该对象将是不同可能类的实例,但在编译时我不知道它将是什么类(取决于用户行为)。,c++,class,oop,C++,Class,Oop,有没有一种方法可以声明和定义一个函数,该函数将向访问该未知类方法的对象返回完整的函数地址 我已经尝试使用boost::variant(下面的示例),但后来我无法访问该类的方法: typedef boost::variant<TWSoldier*, TWMedic*> myvariant; ... myvariant Example = FunctionReturningClassReference(2); std::cout << Example->PrintInf

有没有一种方法可以声明和定义一个函数,该函数将向访问该未知类方法的对象返回完整的函数地址

我已经尝试使用boost::variant(下面的示例),但后来我无法访问该类的方法:

typedef boost::variant<TWSoldier*, TWMedic*> myvariant;
...
myvariant Example = FunctionReturningClassReference(2);
std::cout << Example->PrintInfo() << std::endl;

Error   C2819   type 'boost::variant<TWSoldier *>' does not have an overloaded member 'operator ->' 
Error   C2039   'PrintInfo': is not a member of 'boost::variant<TWSoldier *>'   TotalWar
typedef boost::variant myvariant;
...
myvariant示例=函数ReturningClassReference(2);

std::cout PrintInfo()Evg的评论很有帮助,多态性是一个答案。幸运的是,这个函数可以返回的所有类都是同一个“父类”,我只是简单地声明了函数类型作为指向父类的指针,它就工作了

要访问类方法,您需要知道它的类型。使用多态类怎么样?
variant
现在是标准库的一部分。阅读如何使用它。你可以使用