简体   繁体   English

是否可以在 C++ 中将类作为函数的参数传递

[英]Is it possible to pass a class as an argument of a function in C++

Here is some pseudo code of what I would like to do:这是我想做的一些伪代码:

void thing (storedClassArg){
    virtualClass<x,y> in1 = new storedClassArg<x,y>;
    virtualClass<x,z> in2 = new storedClassArg<x,z>;
}
 
main:
storedClass;
if( inputThingy)
    storedClass = type1;
else
    storedClass = type2;
thing(storedClass);

Short answer: no.简短的回答:没有。

You can't pass a class as an argument to a function.您不能将类作为参数传递给函数。 You can only pass a value .你只能传递一个 A value refers to either an object or a function.值指的是对象或函数。

You can pass a class as an argument to a template.可以将类作为参数传递给模板。 However, template arguments must be determined at compile-time, not run-time.但是,模板参数必须在编译时确定,而不是在运行时确定。

C++ provides run-time polymorphism only through inheritance. C++ 仅通过继承提供运行时多态性。 If you want to create an object whose type will not be known until run-time, what you can do is to make all possible types you might want to create derived classes of a common base.如果您想创建一个直到运行时才知道其类型的对象,您可以做的是创建所有可能的类型,您可能希望创建一个公共基类的派生类。

Even still, you can't use the type itself , that you want to create, as an argument to a function.即使如此,您也不能将要创建的类型本身用作函数的参数。 You'll have to pass in some other value and then branch on that to determine which type you want to create at run-time.您必须传入一些其他值,然后对其进行分支以确定要在运行时创建的类型。

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

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