我可以将指针作为指针转向课程,以便我可以使用分配给同类指针的任何内容
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?
我在程序中有两个同一类的对象。我将重点对象设置为第三个变量,即指针。因此,我可以使用该第三个指针变量切换集中的对象,并且可以在代码的每个部分访问,而不必知道哪个对象是聚焦的。
这看起来如下:
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
放置的相同选择。
相关文章:
- 函数向量_指针有不同的原型,我可以构建一个吗
- 我可以制作指向智能指针的智能指针吗?
- 在C++中,如果我可以直接将整数分配给指针而不使用"new",为什么要使用"new"?
- 如果我在 const 函数上使用指针,我可以返回什么?
- 我可以有一个 ELI5 作为参考和指针以及何时使用它们吗?
- 我可以使用 decltype() 或其他东西通过指针获取真实类型吗?
- 我可以做些什么来改进指针向量中的此搜索?
- 如何将 c++ 类包装到 python 中,以便我可以使用 pybind11 访问其成员的公共方法(成员是一个对象指针)
- 如果我知道只会使用现有元素,我可以在数组开头之前传递指针吗?
- 我可以直接为指针分配地址吗?如果是,如何做到这一点
- 我可以在初始化之前使用 std::array 成员变量中的 data() 指针吗?发出警告
- 为什么我可以通过原始指针而不是shared_ptr来修改对象
- 为什么我可以通过野生指针调用成员函数
- 在C++我可以在不在本地声明结构的情况下将结构作为指针传递吗?
- 为什么我可以取消引用指向抽象类的指针?
- 我可以保证以负偏移访问指针吗?
- 我可以更改将引用参数传递到指针中并使其正常工作的函数的输入(C、C++)吗?
- 我可以从构造函数内传递会员函数指针吗?
- 为什么我可以更改指针的常数(const char *)槽的值
- 我可以依靠 initializer_list::const_iterator 是一个普通的指针吗?