我可以将指针作为指针转向课程,以便我可以使用分配给同类指针的任何内容

Can I pass a pointer as a pointer to a class, so I can use the whatever is assigned to the pointer in the class?

本文关键字:指针 我可以 分配 可以使 同类 任何内      更新时间:2023-10-16

我在程序中有两个同一类的对象。我将重点对象设置为第三个变量,即指针。因此,我可以使用该第三个指针变量切换集中的对象,并且可以在代码的每个部分访问,而不必知道哪个对象是聚焦的。

这看起来如下:

class MainClass
{
    OtherClass otherClass;
    Field fieldA;
    Field fieldB;
    Field *focusedField = &fieldA;
    void someMethod(){
         otherClass.othermethod();         
         focusedField = &fieldB;
         
         otherClass.othermethod();
    }
    void MainClass()
      : otherClass(focusedField);
    {
        
    }
}

,但是现在我想在这样的其他类中使用此指针:

class OtherClass{
    OtherClass(Field *f){
        focusedField = f;
    }
    Field *focusedField;
    
    void otherMethod(){
        std::cout << focusedField->getState() << std::endl;
    }
}

这部分作用...
elethmethod方法的第一个呼叫使用了正确的fielda,但是在我将其更改为fieldb之后的第二个呼叫仍在使用fielda。

我想实现这一点,我将重点的场地传递给其他班级,如果我在主阶段更改它,它会改变。

在J. S.的评论上进行扩展,如果您想"跟踪"一个值,请存储指针或对其进行引用。如果值本身是指指针,那仍然是正确的。对于const-correctness,您应该将OtherClass成员(和构造函数参数(声明为Field *const &,因为它不需要更改Field的焦点。如果它也不需要写入任何集中的Field,请使用const Field *const &

值得注意的是,使用指针作为成员可能会更好(因为它允许作业具有通常的语义(和构造函数参数(宣传临时性是不合适的参数(。它仍然具有相同的共享目的,并允许const放置的相同选择。

相关文章: