第一次使用Stackoverflow!我是C ++和OOP的新手,目前在尝试使用C ++设计StateChart时遇到问题。
我找到了一些文档,这些文档解释了如何创建具有n个状态的状态机以及一个模拟交通信号灯中红绿黄转换的代码示例。
我报告以下代码:
标题
class TLState
{
public:
virtual void Handle() = 0;
};
class TLNetTraffic
{
private:
TLState* _state;
public:
TLNetTraffic();
void setState ( TLState* state );
void Handle();
};
class TLRed: public myTLState
{
private:
TLNetTraffic* _context;
public:
TLRed(TLNetTraffic* context);
void Handle();
};
class TLGreen: public TLState
{
private:
TLNetTraffic* _context;
public:
TLGreen(TLNetTraffic* context);
void Handle();
};
class TLYellow: public TLState
{
private:
TLNetTraffic* _context;
public:
TLYellow(TLNetTraffic* context);
void Handle();
};
cpp
#include "classes.h"
#include <iostream>
TLNetTraffic::TLNetTraffic()
{
_state = new TLRed(this);
}
void TLNetTraffic::setState ( TLState* state )
{
_state = state;
}
void TLNetTraffic::Handle ()
{
_state->Handle();
}
TLRed::TLRed(TLNetTraffic* context): _context(context) {}
void TLRed::Handle()
{
std::cout << "Red Light" << std::endl;
_context->setState( new TLGreen(_context) );
}
TLGreen::TLGreen(TLNetTraffic* context): _context(context) {}
void TLGreen::Handle()
{
std::cout << "Green Light" << std::endl;
_context->setState( new TLYellow(_context) );
}
TLYellow::TLYellow(TLNetTraffic* context): _context(context) {}
void TLYellow::Handle()
{
std::cout << "Yellow Light" << std::endl;
_context->setState( new TLRed(_context) );
}
我的问题是:我想为每个较高状态扩展带有子状态的示例,例如Red_1,Red_2,Red_3,Green_1,Green_2,Green_3,Yellow_1,Yellow_2,Yellow_3 ...
现在,我想到的最简单的事情是“考虑”同一状态下的所有状态并使用上面报告的结构。我个人不喜欢这种解决方案,并且我想知道是否可以实现更好的设计。我试图按如下方式修改代码(我只报告“红色”类):
class myTLState
{
public:
virtual void Handle() = 0;
};
class myTLState_internal //NEW VIRTUAL CLASS
{
public:
virtual void Handle() = 0;
};
class myTLNetTraffic
{
private:
myTLState* _state;
public:
myTLNetTraffic();
void setState ( myTLState* state );
void Handle();
};
class myTLRed: public myTLState
{
private:
myTLNetTraffic* _context;
myTLState_internal* _internal_state; //NEW POINTER TO THE NEW VIRTUAL CLASS
public:
myTLRed(myTLNetTraffic* context);
void Handle();
void setState ( myTLState_internal* _internal_state );
};
class myTLRed_internal1: public myTLState_internal
{
private:
myTLRed* _internal_context;
public:
myTLRed_internal1(myTLRed* context);
void Handle();
};
class myTLRed_internal2: public myTLState_internal
{
private:
myTLRed* _internal_context;
public:
myTLRed_internal2(myTLRed* context);
void Handle();
};
我在cpp中添加了以下内容:
myTLRed::myTLRed(myTLNetTraffic* context): _context(context)
{
_internal_state = new myTLRed_internal1(this);
}
myTLRed_internal1::myTLRed_internal1(myTLRed* context): _internal_context(context){}
我收到以下错误消息:对'vtable for myTLRed_internal1'的未定义引用
老实说,既不知道那是什么,也不知道这是否是正确的方法。任何帮助将非常感激。非常感谢,对于冗长的帖子深表歉意。
对所有指出存在大量内存泄漏的人进行编辑:您完全正确,我知道这一点,但是为了简单起见,只报告了代码。避免内存泄漏的下一个改进是使用智能指针,这是我的计划。