如何将指针作为双指针传递给类的指针属性?

时间:2012-02-14 03:01:01

标签: c++ pointers parameters

我无法弄清楚如何正确传递这个双指针......没有我尝试过的作品...

class myClass{

    MyClass *attribClass;
}

void derp(MyClass **myA) {
    // recursively calls down classes....
    derp(&(myA->attribClass)); // what am i doing wrong?
}

int main() {

    MyClass *myClass = new MyClass;

    myClass.attribClass = *whatever code to initialize a long linked list of MyClass's*;

    derp(&myClass); 
}

3 个答案:

答案 0 :(得分:3)

有几个问题:

class MyClass {  //  Change to "MyClass".

public:   //  Need to make it public or it can't be accessed by "derp()"
          //  Did you intend "derp()" to be a class member?

    MyClass *attribClass;
}; //  missing semicolon

void derp(MyClass **myA) {
    // recursively calls down classes....
    derp(&((*myA)->attribClass)); // what am i doing wrong?
}

在最后一个中,您需要在访问myA之前尊重attribClass

derp(&((*myA)->attribClass)); // what am i doing wrong?

答案 1 :(得分:1)

myA是指向指针的指针,因此您需要取消引用它以获取可以使用->的指针,因此:

derp(&(myA->attribClass));

应该是

derp(&((*myA)->attribClass));

我假设您需要更改/设置指针的值。如果你不是,你可能不应该在这里使用双指针。

答案 2 :(得分:1)

myA需要额外取消引用,其类型为MyClass **(不仅仅是MyClass *):

derp(&(*myA)->attribClass);