简体   繁体   English

如何将对象作为参数传递给类

[英]how to pass an object to class as a parameter

If i have several similar classes, and i have to perform the same set of functions accessing each class, So i thought of making a generic function which takes the class and pointer as parameter. 如果我有几个相似的类,并且我必须执行访问每个类的相同功能集,那么我考虑制作一个通用函数,该函数将类和指针作为参数。 how to do that? 怎么做?

for example: 例如:

   CClass1 * pClass1 = "something";
   CClass2 * pClass2 = "something";
   CClass3 * pClass3 = "something";

pClass1, pClass2 and pClass3 are being used in a similar way, so i need to make a generic function passing pClass1,2,3 as parameters instead of repeating the function for three pointers.. so is ther any way in which u can send the class as well as object as a parameter?? pClass1,pClass2和pClass3的使用方式相似,因此我需要制作一个以pClass1,2,3作为参数的泛型函数,而不是对三个指针重复该函数。因此,您可以通过任何方式发送类以及对象作为参数?

I am not sure if I get your question right: The normal way in C++ to have common function for classes is to derive all classes from the very same basis class. 我不确定是否能正确回答您的问题:C ++中具有类通用功能的通常方法是从完全相同的基类派生所有类。

Beside of that, you can overload functions and operators. 除此之外,您还可以重载函数和运算符。 Then, you can apply the same (by name) function but call the function for the proper type. 然后,您可以应用相同的(按名称)函数,但为正确的类型调用该函数。

While your example code does not make sense, it seems like you are describing something which can be done using templates: 虽然示例代码没有意义,但似乎您正在描述可以使用模板完成的操作:

template<class T>
void do_something() {
    T t = "something";
}

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

相关问题 如何在.dll类方法参数中传递对象? - How to pass an object in a .dll Class Method parameter? 如何在C ++中将类(不是对象)作为参数传递 - How to pass a class (not an object) as a parameter in C++ 将参数传递给参数类对象 - Pass arguments to a parameter class object 如何将类作为参数传递 - How to pass a Class as Parameter 如何将一个对象作为另一个类构造函数的参数传递? - How to pass an object as another class constructor's parameter? 如何将子类作为期望基类的函数的参数传递,然后将该对象传递到指向这些抽象类对象的指针向量中? - how to pass subclass as parameter for function expecting base class then pass that object into vector of pointers to those abstract class objects? 我们如何在没有使用指针的情况下将派生的 class 的 object 作为参数传递给 function 中的 function? - How can we pass object of derived class as a parameter to a function in base class without using pointer? 在创建派生类Object时将参数传递给基类构造函数 - Pass Parameter to Base Class Constructor while creating Derived class Object 非类型模板参数:如何传递对基类对象的引用? - non-type template parameter : how to pass reference to base class object? 如何将数组对象(Class Template c ++)作为参数传递给函数? - How do I Pass an array object (Class Template c++) to a function as a parameter?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM