[英]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;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.