[英]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?
I have two objects of the same class in my program.我的程序中有两个相同类的对象。 I set the focused object to a third variable, which is a pointer.
我将焦点对象设置为第三个变量,它是一个指针。 So I can switch the focused object with this third pointer variable and have access at every part of my code without having to know which object is focused.
因此,我可以使用第三个指针变量切换焦点对象,并且可以访问代码的每个部分,而无需知道哪个对象是焦点。
This looks like the following:如下所示:
class MainClass
{
OtherClass otherClass;
Field fieldA;
Field fieldB;
Field *focusedField = &fieldA;
void someMethod(){
otherClass.othermethod();
focusedField = &fieldB;
otherClass.othermethod();
}
void MainClass()
: otherClass(focusedField);
{
}
}
But now I want to use this pointer in another class like this:但现在我想在另一个类中使用这个指针,如下所示:
class OtherClass{
OtherClass(Field *f){
focusedField = f;
}
Field *focusedField;
void otherMethod(){
std::cout << focusedField->getState() << std::endl;
}
}
And this works partly...这部分有效......
The first call of the otherMethod method uses the fieldA, which is correctly, but the second call, after I changed it to fieldB, is still using fieldA. otherMethod 方法的第一次调用使用了 fieldA,这是正确的,但是在我将其更改为 fieldB 之后的第二次调用仍然使用 fieldA。
I want to achieve that I pass the focusedField to the OtherClass and it changes if I change it in the MainClass.我想实现将focusedField 传递给OtherClass 并且如果我在MainClass 中更改它,它会更改。
To expand on JS's comment , if you want to “track” a value, you store a pointer or reference to it.扩展JS 的注释,如果你想“跟踪”一个值,你可以存储一个指针或对它的引用。 That's still true if the value is itself a pointer.
如果值本身是一个指针,这仍然是正确的。 For const-correctness, you should declare the
OtherClass
member (and constructor parameter) as Field *const &
since it doesn't need to change which Field
is focused.对于常量正确性,您应该将
OtherClass
成员(和构造函数参数)声明为Field *const &
因为它不需要更改哪个Field
是焦点。 If it doesn't need to write to whatever focused Field
either, use const Field *const &
.如果它也不需要写入任何重点
Field
,请使用const Field *const &
。
It's worth noting that using a pointer to pointer might be better both as a member (because it allows assignment to have the usual semantics) and as a constructor parameter (to advertise that a temporary is inappropriate as an argument).值得注意的是,使用指向指针的指针作为成员(因为它允许赋值具有通常的语义)和构造函数参数(宣传临时不适合作为参数)可能会更好。 It still serves the same sharing purpose and allows the same choices of
const
placement.它仍然服务于相同的共享目的,并允许相同的
const
放置选择。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.