C++类的成员在类外更新
C++ member of class updated outside class
我有一个关于C++中的指针和引用的问题。我是一名程序员,通常用C#和PHP编程。
我有两个类(目前(,如下所示。控制器中的 X/Y 不断变化,但我希望它们在命令中保持最新状态。我有多个命令,如前进、转动、后退等。
当我发出命令时,我给他们控制器,但控制器的状态(X,Y(每秒更新一次。
如何修复命令中的控制器属性也每秒更新的问题?
class Forward : ICommand
{
Controller ctrl;
void Execute() {
int CurrentX = ctrl.X;
int CurrentY = ctrl.Y;
//Check here for the current location and calculate where he has to go.
}
}
class Controller
{
int X;
int Y;
void ExecuteCommand(ICommand command) {
command.Execute();
}
}
主.cpp
Controller controller;
Forward cmd1 = new Forward(1, controller);
Turn cmd2 = new Turn(90, controller);
Forward cmd3 = new Forward(2, controller);
controller.Execute(cmd1);
controller.Execute(cmd2);
controller.Execute(cmd3);
我已经阅读了一些关于指针和引用的内容,我认为我必须使用它,但不知道如何在这种情况下使用它。
(代码可能会有一些语法错误,但那是因为我键入了。除了更新之外,一切都在进一步工作(。
如果使用引用而不是复制对象,则可以看到更改。
#include <iostream>
using namespace std;
class ICommand
{
public:
virtual ~ICommand() = default;
virtual void Execute() = 0;
};
class Controller
{
public:
int X = 0;
int Y = 0;
void ExecuteCommand(ICommand & command) {
// ^-------
command.Execute();
}
};//,--- semicolons required
class Forward : public ICommand //note public
{
const int step;
Controller ctrlCopy;
Controller & ctrlReference;
public:
Forward(int step, Controller & ctrl) :
step(step),
ctrlCopy(ctrl), //this is a copy of an object
ctrlReference(ctrl) //this is a reference to an object
{
}
void Execute() {
std::cout << "copy: " << ctrlCopy.X << ", " << ctrlCopy.Y << 'n';
std::cout << " ref: " << ctrlReference.X << ", " << ctrlReference.Y << 'n';
//Check here for the current location and calculate where he has to go.
ctrlCopy.X += 10;
ctrlReference.X += 10;
}
};//<--- semicolons required
int main() {
Controller controller;
Forward cmd1(1, controller);
//Turn cmd2(90, controller); //Left for the OP to do
Forward cmd3(2, controller);
controller.ExecuteCommand(cmd1);
//controller.ExecuteCommand(cmd2);
controller.ExecuteCommand(cmd3);
//Do it again to show the copy and reference difference
std::cout << "Once more, with feelingn";
controller.ExecuteCommand(cmd1);
controller.ExecuteCommand(cmd3);
}
给
copy: 0, 0
ref: 0, 0
copy: 0, 0 // [1]
ref: 10, 0 // [2]
Once more, with feeling
copy: 10, 0
ref: 20, 0
copy: 10, 0
ref: 30, 0
1 表示副本的 X 和 Y 为 0,而 [2] 中显示的引用已按规定的步长移动(以 controller.ExecuteCommand(cmd3)
为单位(
请注意,我们不需要使用new
来完成这项工作(如果您使用 new,请不要忘记delete
(。
此外,void ExecuteCommand(ICommand command)
现在采用引用,否则按值副本会"切片"(例如,请参阅此处(
相关文章:
- 类的成员数据未更新
- C++:更新类的向量成员变量
- Qml 未收到基类成员变量的更新值
- C++ 矢量的成员未更新
- 从成员变量更新类变量或调用类功能是给出运行时错误
- 更新成员集合使用STL给定输入收集
- C++ - 类未正确更新成员
- C++类的成员在类外更新
- 构造函数不更新类成员变量
- 带有boost ::信号的自动更新依赖性类成员
- 如果您在c++中更新一个集合的成员,该集合会自动更改顺序吗
- 使用指针对指针可以解决类成员不更新的问题吗?如果是,如何
- 为向量成员和更新元素指定默认值
- 成员变量在评估前未正确更新
- "has-a"点类成员数据的矩形类。使用 Point 类的成员函数时,成员数据不会更新
- 成员变量的更新值不会在 PTHREAD 中的线程路由函数中重新排列
- C++ 成员变量未更新 - 菜鸟在这里
- 从Boost signals2信号调用的函子的成员变量不更新
- 更新函数调用中的静态成员会导致崩溃
- Boost序列化:在反序列化时更新成员