c++ - 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 pass vector via function call pointer vector in class , call function or element via receiving class; , how call function in receiving class remotely?
in example, object0 object type containing function called.
object0 created in object1 member of vector.
then vector passed object2, wherein called external object; here arbitrarily chosen within object1;
main() way of booting app up, , welcome suggestions on improving it.
#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 line working? _object2.object0vec[0].function();
} }; int main() { object1 newobject1; object1 &ref_newobject1 = newobject1; ref_newobject1.init(); }
in init():
"_object2" has lifetime same object1. yet, in init() presumably pass pointer local variable object0vec knowvector(). now, "_object2" has longer lifetime object has poiner to, yet doesn't own. "knowvector" make copy of vector instead of keeping pointer.
syntax:
in init(), "_object2" pointer, need use ->.
object2::object0vec pointer while presumably "object0vec[0]" meant first object in vector, not first in array of vectors.
_object2 -> (*object0vec)[0].function();
Comments
Post a Comment