指针赋值指针不起作用

时间:2013-11-09 01:10:15

标签: c++ pointers

编辑:我已将func2()中的意外参数错误修正为MyClass*而不是MyClass

我有一个这样的课程:

#include "MyClass.h"

class X{
    public:
        X();
        MyClass* m;
        func1();
        func2(MyClass* m, int x);

    private:
}

来源:

#include "X.h"

X::X{
    m = null_ptr;
}

X::func1(){
    //Pass the un-initialized data member m here...
    func2(m, 6);

    //When I get to this point m has not been assigned, even though it was passed as a pointer to func2()
}

X::func2(MyClass* old_obj, int x){
    //Please forgive the memory management for a second....
    MyClass* new_obj = new MyClass(x);

    //This should initialise the data member m??????
    old_obj = new_obj ;
}

然而它不起作用 - 我在这里做了一个基本的错失假设吗?我以为这会起作用....

1 个答案:

答案 0 :(得分:6)

要修改函数参数的指针,您需要修改原始指针而不是它的副本。

 func2(MyClass*& m, int x);
 //            ^