2015-10-31 59 views
0

我甚至不知道我可能怎么称呼它。 可以说我想从一个实例化这个类的方法调用一个实例化的类。 (可能是很难理解)如何从另一个函数访问实例化类?

在java中我只是这样做:

public class MyClass { 

    ExampleClass classIwantToAccess; // This line here is the important part. 

    public MyClass() 
    { 
     classIwantToAccess = new ExampleClass(); 
    } 

    public ExampleClass getWanted() 
    { 
     return classIwantToAccess; 
    } 
} 

所以,我想在C++中,但它不工作像我预期的...

#include "Test.h" 

Test test; 

void gen() 
{ 
    test = Test::Test("hello"); 
} 

int main() 
{ 
    // How can I access my class from here? 
    return 0; 
} 
+0

你忘了包含'Test.h' – sehe

回答

0

我不确定你想要实现什么,但是如果你想分开声明从它的初始化你可以使用指针。

因为现在你有类似的东西:Test test; - 它会调用类Test的构造函数。为了避免这种情况,你可以使用指针并像这样写:Test *test; - 现在test只会是一个指向某个对象的指针。

然后你可以在另一个函数中创建(分配)这个对象。所以,你的整个代码会看起来像:

#include "Test.h" 

Test *test; 

void gen() 
{ 
    test = Test::Test("hello"); //Func Test has to be static and 
           //it has to return pointer to Test. 
           //Or you can use new Test("hello") here. 
} 

int main() 
{ 
    //Now you can dereference pointer here to use it: 
    test->foo(); //Invoke some function 
    return 0; 
} 

而不是原始指针可以使用例如shared_ptr的智能指针,将在java中采取的内存管理的护理,如:

#include "Test.h" 
#include <memory> 

std::shared_ptr<Test> test; 

void gen() 
{ 
    test = std::make_shared<Test>("Hello"); 
} 

int main() 
{ 
    //You use it as normal pointer: 
    test->foo(); 
    return 0; 
} 
+0

啊指针是解决方案!很好,谢谢! – ElKappador

相关问题