如何了解C++中虚空数组的元素类型
首先,我在做编译器项目,我已经建立了一个符号表如何了解C++中虚空数组的元素类型,c++,casting,void-pointers,C++,Casting,Void Pointers,首先,我在做编译器项目,我已经建立了一个符号表 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
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可以是函数、类、变量、作用域,它们都是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什么的!!!
为什么??我怎样才能修好它??或者如何知道必须转换什么数据类型。传统的答案是向MapElem添加枚举以指示类型:
class MapElem{
//Enumeration identifying all the types of map element and indicating the contents of elem.
typedef enum {
aFunction,
aClass,
aVariable,
aScope
} Type;
char* name;
Type type; //<---- Tells us what elem really is!
void* elem;
MapElem * next;
...
};
更为面向对象的方法是为每种类型引入基类和子类。
您可能会发现这有点麻烦,因为变量类型function、class、variable和scope是如此的不同,以至于您的基类只包含一种提取类型的方法!
哦,还有一些方法,返回一个可打印的字符串来检查元素
您可以引入一个返回枚举类型或依赖RTTI的虚拟成员。
RTTI通常是一个错误,表明您不理解多态性,或者它对情况没有帮助。
在这种情况下,我怀疑后者。首先不要丢弃类型信息。这是RTTI或虚拟函数的一个工作。Stasic Studio在运行时不执行任何检查。您应该使用C++容器,例如STD::map@user3312095-简单地说,没有魔法可以从空指针获取类型信息。看起来您误解了static_cast所做的事情,并根据这些错误信息编写了一系列代码。