C++类的成员在类外更新

C++ member of class updated outside class

本文关键字:更新 成员 C++      更新时间:2023-10-16

我有一个关于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)现在采用引用,否则按值副本会"切片"(例如,请参阅此处(