c++实现设计模式中的命令模式,输出结果不正确.

小小白杨123 2014-04-22 10:32:19
#include<iostream>
#include<string>
using namespace std;

class Light{
public:
Light(string s);
void on();
void off();
protected:
string concretelight;
};

class Command{
public:
virtual void execute(){};
};

class noCommand:public Command
{
public:
void execute(){};
};

class LightOnCommand:public Command{
public:
LightOnCommand(Light &light);
void execute();
private:
Light *plighton;
};

class LightOffCommand:public Command{
public:
LightOffCommand(Light &light);
void execute();
private:
Light *plightoff;
};

class RemoteControl
{
public:
RemoteControl();
void setCommand(int slot,Command &onCommand,Command &offCommand);
void onButtonWasPressed(int slot);
void offButtonWasPressed(int slot);
private:
Command *onCommands[];
Command *offCommands[];
};

Light::Light(string s)
{
concretelight=s;
}

void Light::on(){
cout<<concretelight<<"light is on"<<endl;
}

void Light::off(){
cout<<concretelight<<"Light is off"<<endl;
}

LightOnCommand::LightOnCommand(Light &light){
plighton=&light;
}

void LightOnCommand::execute(){
plighton->on();
}

LightOffCommand::LightOffCommand(Light &light){
plightoff=&light;
}

void LightOffCommand::execute(){
plightoff->off();
}

RemoteControl::RemoteControl()
{
noCommand nocommand;
for(int i=0;i<1;i++)
{
onCommands[i]=&nocommand;
offCommands[i]=&nocommand;
}
}

void RemoteControl::setCommand(int slot,Command &onCommand,Command &offCommand)
{
onCommands[slot]=&onCommand;
offCommands[slot]=&offCommand;
}

void RemoteControl::onButtonWasPressed(int slot)
{
onCommands[slot]->execute();
}

void RemoteControl::offButtonWasPressed(int slot)
{
offCommands[slot]->execute();
}

int main(){
Light light("Kitchen");
RemoteControl remotecontrol;
LightOnCommand lighton=LightOnCommand(light);
LightOffCommand lightoff=LightOffCommand(light);
remotecontrol.setCommand(0,lighton,lightoff);
remotecontrol.onButtonWasPressed(0);
remotecontrol.offButtonWasPressed(0);
return 0;
}


为什么输出结果是两个kttchen light is off.应该是kitchen light is on和kitchen light is off啊.
...全文
146 4 打赏 收藏 转发到动态 举报
写回复
用AI写文章
4 条回复
切换为时间正序
请发表友善的回复…
发表回复
赵4老师 2014-04-23
  • 打赏
  • 举报
回复
代码功能归根结底不是别人帮自己看或讲解或注释出来的;而是被自己静下心来花足够长的时间和精力亲自动手单步或设断点或对执行到某步获得的中间结果显示或写到日志文件中一步一步分析出来的。 提醒:再牛×的老师也无法代替学生自己领悟和上厕所! 单步调试和设断点调试是程序员必须掌握的技能之一。
ri_aje 2014-04-23
  • 打赏
  • 举报
回复

RemoteControl::RemoteControl()
{
    noCommand nocommand;
    for(int i=0;i<1;i++)
    {
        onCommands[i]=&nocommand;
        offCommands[i]=&nocommand;
    }
}
on/off commands 需要分配内存才能够使用,比如。

onCommands = new Command [10];
别忘了,delete []。 用 std::vector 更好。
小小白杨123 2014-04-23
  • 打赏
  • 举报
回复
我已经弄过断点调试过了,函数总是跳转不到正确的地方,我实在看不出错误啊。
xiaohuh421 2014-04-23
  • 打赏
  • 举报
回复
调试就知道拉, 下断点, 调试, 看为什么会输出两次一样的.

65,208

社区成员

发帖
与我相关
我的任务
社区描述
C++ 语言相关问题讨论,技术干货分享,前沿动态等
c++ 技术论坛(原bbs)
社区管理员
  • C++ 语言社区
  • encoderlee
  • paschen
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
  1. 请不要发布与C++技术无关的贴子
  2. 请不要发布与技术无关的招聘、广告的帖子
  3. 请尽可能的描述清楚你的问题,如果涉及到代码请尽可能的格式化一下

试试用AI创作助手写篇文章吧