我有如下类结构
并定义有:
BaseToken lastToken;
1
有一个地方需要判断 lastToken 是否是 KeywordToken
if(dynamic_cast<KeywordToken *>(lastToken)){}
1
但是编译时报错如下:
LexicalAnalyzer.cpp|444| error: cannot dynamic_cast
((LexicalAnalyzer*)this)->LexicalAnalyzer::lastToken’ (of type
class BaseToken’) to type `class KeywordToken*’ (source is not a pointer)
貌似不能将父类型转为子类型,那么请问如何判断 lastToken
是 KeywordToken
?
dynamic_cast < type-id > ( expression )
The type-id must be a pointer or a reference to a previously defined class type or a “pointer to void”. The type of expression must be a pointer if type-id is a pointer, or an l-value if type-id is a reference.
dynamic_cast
需要的是一个指针,将代码改为如下即可:
if(dynamic_cast<KeywordToken *>(&lastToken)){}
1