如何从另一个函数访问实例化的类

How to access a instanciated class from another function?

本文关键字:实例化 访问 函数 另一个      更新时间:2023-10-16

我甚至不知道怎么能调用它。比方说,我试图从一个方法调用一个实例化的类,而不是实例化这个类的方法。(可能很难理解)

在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;
}

我不确定您想要实现什么,但如果您想将类的声明与其初始化分离,则可以使用指针。

因为现在您有了类似的东西: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;
}