我对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();
}
}
Main.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);
我已经阅读了有关指针和引用的内容,我认为我必须使用它,但在这种情况下不知道如何使用它。
(代码可能有一些语法错误,但那是因为我输入了。除了更新之外,一切都在进行进一步的工作。)
答案 0 :(得分:1)
如果使用引用而不是复制对象,则可以看到更改。
#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 feeling\n";
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
来完成这项工作(如果您使用新功能,请不要忘记delete
。)
此外,void ExecuteCommand(ICommand command)
现在采用引用,否则按值复制&#34;切片&#34; (例如,见here)