简体   繁体   English

指向具有指针成员的对象的指针

[英]Pointer to an object that has a pointer member

Are pointers to pointers legal in c++? 指针在C ++中合法吗? I've come across this SO question: Pointer to Pointer to Pointer 我遇到了这样的问题: 指针到指针指针到指针

But the answers aren't clear if it is legal c++ or not. 但是答案尚不清楚,是否合法的c ++。 Let's say I have: 假设我有:

class A{
public:
    void foo(){
        /* ect */
    }
};

class B{
public:
    A* a;
    /* ect */
};

void Some_Func() {
    B *b;

    // besides this looking ugly, is it legal c++?
    b->a->foo();
};

Is the line b->a->foo() OK to write? b->a->foo()行可以写吗? Is there a better way to represent this expression? 有没有更好的方法来表示此表达式?

This is perfectly valid.But the term you are using " pointer to pointer " is wrong. 这是完全正确的。但是您使用的“ 指针指向指针 ”一词是错误的。

the term means a double pointer like **P , a pointer which holds the address of another pointer . 该术语表示像**P这样的双指针, 一个指针持有另一个指针的地址

but your case is the pointer(of class A) is an member of a class whose pointer(of class B) is created by you in some_func 但您的情况是指针(类A)是类的成员,该类的指针(类B)由您在some_func创建

Illegal, "a" is private. 非法“ a”是私有的。 So is "foo". “ foo”也是如此。

If corrected to "public" then they're legal constructs. 如果更正为“公开”,那么它们就是法律依据。

From your code its hard to find a "better" way. 从您的代码中很难找到一种“更好”的方法。 BUT You can modify the code to make the code look much clearer: 但是您可以修改代码以使代码看起来更清晰:

class A{
public:
    void foo(){ cout << "Work";}
};

class B{
private:
    A *a;
public:
    A& getA(){
       return *a;
    }
};

void SomeFunction()
{
    B *b = new B();
    B& bRef = *b;
    bRef.getA().foo(); //better looking code? 
        delete b;
}

It is legal but in your example your program will crash (if you could compile it since your members are private) because you did not create an instance of B 这是合法的,但在您的示例中,您的程序将崩溃(如果您可以编译它,因为您的成员是私有的),因为您没有创建B的实例

void Some_Func() {
    B *b;  // uninitialized B ptr  should be   B* b = new B;

    // legal
    b->a->foo();
};

Although you may want to reconsider accessing variables directly as you do and instead have getter/setters to access private member variables. 尽管您可能希望像重新做一样重新考虑直接访问变量,而是让getter / setter访问私有成员变量。

Yes but then you have to use pointer to pointer like **P . 是的,但是您必须使用**P类的指针。
Actually if we want to access a pointer which is holding another pointer then we can do this.This is allowed in c++ but keep in mind that only in case if you have assigned a pointer to pointer p 实际上,如果我们要访问包含另一个指针的指针,则可以执行此操作.c ++允许这样做,但请记住,只有在您将指针分配给pointer p

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM