java - How to access a instanciated class from another function? -


i don't know how possibly call this. lets i'm trying call instantiated class method other 1 instantiated class. (might hard understand)

in java this:

public class myclass {      exampleclass classiwanttoaccess; // line here important part.      public myclass()     {         classiwanttoaccess = new exampleclass();     }      public exampleclass getwanted()     {         return classiwanttoaccess;     } } 

so tried in c++, doesn't work expected...

#include "test.h"  test test;  void gen() {     test = test::test("hello"); }  int main() {     // how can access class here?     return 0; } 

i'm not sure you're trying achieve, if want separate declaration of class it's initialization can use pointers.

because have that: test test; - invoke constructor of class test. avoid can use pointers , write that: test *test; - test pointer object.

then can create (allocate) object in function. whole code that:

#include "test.h"  test *test;  void gen() {   test = test::test("hello");  //func test has static ,                                 //it has return pointer test.                                //or can use new test("hello") here. }  int main() {   //now can dereference pointer here use it:   test->foo();  //invoke function   return 0; } 

instead of raw pointer can use smart pointer example shared_ptr take care of memory management, in java:

#include "test.h" #include <memory>  std::shared_ptr<test> test;  void gen() {   test = std::make_shared<test>("hello"); }  int main() {   //you use normal pointer:   test->foo();     return 0; } 

Comments

Popular posts from this blog

django - (fields.E300) Field defines a relation with model 'AbstractEmailUser' which is either not installed, or is abstract -

matlab - error with cyclic autocorrelation function -

php - Using grpc in Laravel, "Class 'Grpc\ChannelCredentials' not found." -