我在C ++中遇到以下问题:
class Class3
{
//...
};
class Class1
{
public:
void func1(Class3* class3Pointer)
{
Class3 *myClass3 = new Class3();
//The newly created object myClass3 should be referenced by class3Pointer
class3Pointer = myClass3;
//But I need to work with myClass3 object now in main function below, after myClass3 has been initiated.
//I want to do that while a loop is sleeping
while(true) {
sleep();
}
}
};
class Class2
{
public:
void func2(Class3* class3Pointer)
{
Class1 *Class1Object = new Class1();
Class1Object->func1(class3Pointer);
}
};
int _tmain(int argc, _TCHAR* argv[])
{
Class3* class3Pointer;
Class2 *myClass2 = new Class2();
myClass2->func2(class3Pointer); //Calling in a new thread
//Here, I need to work with object myClass3 instantiated in Class1->func1
return 0;
}
在main方法中,我想用myPointer引用Func2中创建的Object。 我怎样才能做到这一点?我认为,上面的方法是错误的,因为它只是按值传递myPointer两次。如何通过引用传递指针?
感谢您的帮助。用例是tcp套接字编程。
最佳,SpeedyV
答案 0 :(得分:1)
使函数通过引用获取其参数:
void func1(Class3* & class3Pointer)
// ----------------^
然后对函数中class3Pointer
的更改也会改变传递的参数(事实上这两个事物都将表示相同的变量)。