我是C++的新手,正在尝试实现一个海龟模拟器,它将从文本文件中读取命令,将它们放在向量上,并使用glut进行绘制。
我有一个节点类,从节点派生出命令类,4个从命令派生出的类(前进,左转,右转,跳跃,重复)和Prog类,用于存储命令。
class node
{
public:
node();
virtual ~node();
virtual void Run()=0;
};
class command : public node
{
private:
float v;
public:
command();
command(float);
~command();
virtual void Run();
friend istream& Prog::operator>> (istream& in, Prog& pro);
};
并且
class Repeat : public command
{
private:
Prog pg;
public:
Repeat(float value, istream& in);
~Repeat();
void Run();
friend istream& Prog::operator>> (istream& in, Prog& pro);
};
class Prog
{
private:
vector<node*> listing;
public:
Prog();
~Prog();
void Run();
friend istream& operator>> (istream& in, Prog& pro);
};
现在我们可以从文件中读取内容,并将命令写入临时向量,然后跟随它们的值。例如,repeat应该重复以下四个命令:
|repeat|4|forward|4|left|40|forward|10
我们希望在Prog类的listing向量中添加指向基类对象的指针,以便调用4个派生类的Run函数并利用多态性。
我的问题是,我使用while循环遍历我的temp向量,并为找到的每个命令创建一个对象,但我只能使用相同的名称,因为动态命名不能使用(我想)。我认为每个新的Forward命令都会覆盖fw对象。
else if (command=="FORWARD")
{
Forward::Forward fw(value);
node* ptr;
ptr= &fw;
pro.push_back(ptr);
text.erase (text.begin(), text.begin()+2);*/
}
我尝试使用以下类似的方法,但没有找到正确的方式。
else if (command=="FORWARD")
{
Forward::Forward fw(value);
new Forward(fw);
node* ptr;
ptr= &(??);
pro.push_back(ptr);
text.erase (text.begin(), text.begin()+2);*/
有没有办法实现我想要的功能?最终我们希望调用Prog::Run,大致如下:
void Prog::Run()
{
vector<node*>::iterator it;
for (it=listing.begin();it!=listing.end();it++)
listing[it]->Run();
}
关于我声明的友元函数,我不确定是否正确:我在Prog类中定义了friend istream& operator>> (istream& in, Prog& pro);
,并在其他两个类中仅声明它,还是需要为每个类定义它,并在每个类中有一个不同的第二个参数?
提前感谢:)