How to access a instanciated class from another function?

时间:2015-10-31 00:17:35

标签: java c++ class

I don't even know how I could possibly call this. Lets say I'm trying to call a an instantiated class from a method other then one that instantiated this class. (Might be hard to understand) In java I would just do this: public class MyClass { ExampleClass classIwantToAccess; // This line here is the important part. public MyClass() { classIwantToAccess = new ExampleClass(); } public ExampleClass getWanted() { return classIwantToAccess; } } So I tried that in c++, But it doesn't work like I expected... #include "Test.h" Test test; void gen() { test = Test::Test("hello"); } int main() { // How can I access my class from here? return 0; }

1 个答案:

答案 0 :(得分: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;
}