在C++中复制指针

tun*_*nuz 1 c++ parameters pointers copy initialization

我有一个类A,包含两个指向另一个类B的对象的指针.我想初始化一个指针或另一个指针,具体取决于传递给哪一个init(),这也需要其他参数.我的情况如下:

class A {

public:
    A();
    init(int parameter, int otherParameter, B* toBeInitialized);

protected:
    B* myB;
    B* myOtherB;

};
Run Code Online (Sandbox Code Playgroud)

现在我的意思是我想打电话给init():

init(640, 480, this->myB);
Run Code Online (Sandbox Code Playgroud)

要么

init(640, 480, this->myOtherB);
Run Code Online (Sandbox Code Playgroud)

现在,我的init实现为:

void init( int parameter, int otherParameter, B* toBeInitialized ) {

    toBeInitialized = someConstructorFunction(parameter, otherParameter);

}
Run Code Online (Sandbox Code Playgroud)

问题是两个指针没有初始化,我怀疑toBeInitialized被覆盖,但原始参数没有被修改.

我做错了什么?我应该使用指针的引用吗?

谢谢
Tommaso

And*_*nck 6

是的,改为

void init( int parameter, int otherParameter, B*& toBeInitialized ) {

    toBeInitialized = someConstructorFunction(parameter, otherParameter);

}
Run Code Online (Sandbox Code Playgroud)

在原始代码toBeInitialized中按值传递,只会修改变量的本地副本.