[英]How to pass a vector of objects to another class then call a function from within a member of an object in that vector?
How to pass a vector via a function call to a pointer to a vector in another class and call a function or element via the receiving class; 如何通过函数调用将向量传递给另一个类中的向量的指针,以及如何通过接收类来调用函数或元素; and how to call that function in the receiving class remotely?
以及如何在接收类中远程调用该函数?
In this example, object0 is an object type containing a function that will be called. 在此示例中,object0是包含将被调用的函数的对象类型。
Object0 will be created in object1 as a member of a vector. 将在对象1中创建对象0作为向量的成员。
Then that vector will be passed to object2, wherein it will be called from an external object; 然后,该向量将传递给object2,在其中它将从外部对象调用; here arbitrarily chosen as within object1;
这里任意选择在object1内;
main() is just a way of booting this app up, and I would welcome suggestions on improving it. main()只是启动此应用程序的一种方式,欢迎提出改进建议。
#include <vector>
class object0
{
protected:
int a;
void function()
{
std::cout << "function called" << std::endl;
}
};
class object2
{
public:
std::vector<object0> *object0vec;
void knowvector(std::vector<object0> *_object0vec)
{
object0vec = _object0vec;
}
};
class object1
{
public:
object2* _object2;
object1()
{
_object2 = new object2;
}
void init()
{
std::vector<object0> object0vec;
object0vec.push_back(new object0)
_object2.object0vec[0].function();
How to get this line working? 如何使这条线工作? _object2.object0vec[0].function();
_object2.object0vec [0] .function();
}
};
int main()
{
object1 newobject1;
object1 &ref_newobject1 = newobject1;
ref_newobject1.init();
}
In init(): 在init()中:
"_object2" has lifetime the same as object1. “ _object2”的生存期与object1相同。 Yet, in init() you presumably will pass a pointer to the local variable object0vec to knowvector().
但是,在init()中,您大概会将指向本地变量object0vec的指针传递给knowvector()。 So now, "_object2" has a longer lifetime than an object it has a poiner to, yet doesn't own.
因此,现在,“ _ object2”的生存期比其具有Poiner的对象(但不拥有)的寿命更长。 "knowvector" could make a copy of the vector instead of keeping a pointer.
“ knowvector”可以复制该向量,而不是保留一个指针。
Syntax: 句法:
In Init(), "_object2" is a pointer, so you need to use ->. 在Init()中,“ _ object2”是一个指针,因此您需要使用->。
object2::object0vec is also a pointer while presumably "object0vec[0]" is meant to get the first object in the vector, not the first in an array of vectors. object2 :: object0vec也是一个指针,而大概“ object0vec [0]”的意思是获取向量中的第一个对象,而不是向量数组中的第一个对象。
_object2 -> (*object0vec)[0].function();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.