如何从另一个函数访问实例化的类
How to access a instanciated class from another function?
我甚至不知道怎么能调用它。比方说,我试图从一个方法调用一个实例化的类,而不是实例化这个类的方法。(可能很难理解)
在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;
}
相关文章:
- 从模板参数包实例化的访问类实现
- 访问使用接口实例化的类的私有成员
- 从地图访问对象会导致新对象C 的实例化
- QML实例化C 对象.我如何访问他们的方法
- 访问实例化类的变量/函数
- 如何从类内实例化的对象访问私有变量
- 为什么在实例化模板类时编译器无法访问.cpp
- 访问不带实例化对象的非静态成员函数
- 如何从另一个类访问一个类的方法/变量,而不在c++中实例化它或子类
- 为什么在显式实例化中不适当地访问privates是合法的
- 访问实例化类的变量
- 继承错误 - 无法实例化抽象类 无法访问在类中声明的受保护成员
- 访问类的成员。此类的对象从未实例化。所有成员的类型均为静态
- 如何实例化和访问boost mpl类型
- 在实例化之前访问方法
- 方法访问C++中的对象实例化
- 如何从另一个函数访问实例化的类
- '在实例化 [模板类] [成员] 时受到保护 [. .[公共成员] 无法访问'
- 如果模板存在嵌套类型(未访问),且该方法无法编译,则模板可以实例化吗?
- 为什么显式模板实例化存在访问检查漏洞