【发布时间】:2015-01-03 06:23:01
【问题描述】:
首先我在做编译器项目,我已经建立了一个符号表
class SymbolTable
{
Scope * currScope;
Scope * rootScope;
...
}
//where scope is
class Scope{
Scope();
Scope * parent;
MyMap * m;
...
};
//and Mymap is
class MyMap
{
static const int mapLength = MAX_LENGTH;
MapElem * arr[mapLength];
int hash(char* name);
...
}
//MapElem is
class MapElem{
char* name;
void* elem;
MapElem * next;
...
}
现在 Void* elem 可以是 ((function , class, variable ,scope)) 所有的 r 类, 我想打印符号表来检查 Yacc 和解析器在做什么! 我试着这样做:
void printScope(Scope *s)
{
if (s != NULL)
{
cout << "{";
for (int i = 0; i < 71; i++)
{
MapElem* tempelem = s->m->getbyId(i);
while (tempelem != NULL)
{
//cout << "element name is" << tempelem->getName();
if (static_cast <Type*> (tempelem->getElem())){
Type* t = (Type*)tempelem->getElem();
cout << "element is Class it's name is" << t->getIs_final() << " " << t->get_name() << "(";
for (int i = 0; i < t->getInheritedType().size(); i++){
if (t->getInheritedType()[i] != NULL)
cout << t->getInheritedType()[i]->get_name() << "," << endl;
}
cout << "):" << endl;
printScope(t->getScope());
}
else if (static_cast <Function*>(tempelem->getElem())){
Function* t = (Function*)tempelem->getElem();
cout << "element is Function it's name is" << t->get_final() << " " << t->get_name() << "(";
vector<Variable *> paramet = t->getparameters();
for (int i = 0;i< paramet.size(); i++){
cout << paramet[i]->get_name() << "," << endl;
}
cout << "):" << endl;
printScope(t->getScope());
}
else if ((Scope*)tempelem->getElem()){
Scope* t = (Scope*)tempelem->getElem();
printScope(t);
}
else if ((Variable*)tempelem->getElem()){
Variable* t = (Variable*)tempelem->getElem();
cout << "element is Variable it's name is" << t->getAccessModifier() << " " << t->get_name() << endl;
}
tempelem = tempelem->getNext();
}
}
cout << "}"<<endl;
}
}
代码运行完美,但没有检查 If 语句中的 [void type],即使转换错误,也始终输入第一个条件, 以该顺序始终输入类型,即使 void 是函数或变量 ??? 当我更换它们时,也输入第一个 stmt 它是什么! 为什么 ??以及我该如何解决?或者我怎么知道我必须转换什么数据类型。
【问题讨论】:
-
一开始就不要扔掉类型信息。
-
这是 RTTI 或虚函数的工作。
-
static_cast在运行时不执行任何检查。 -
您应该使用 C++ 容器,例如
std::map -
@user3312095 - 简单地说,没有魔法可以从空指针获取类型信息。看来您误解了
static_cast所做的事情,并根据这些错误信息编写了一系列代码。
标签: c++ casting void-pointers