问题描述
我遇到的情况,我发现它很方便的存储基类中的对象的类型(作为枚举),进一步将指向该基类的指针转换为子类指针,取决于它的值类型。
例如:
/ code>和 CLiteralToken 。
如果您随后使用 aTokens [nI] - > doSomething();I'm facing situations where i'm finding it handy to store the type (as an enum) of an object in the base class to further cast a pointer to that base class into a subclass pointer depending on the value of that type.
For example :
class CToken { public: token_type_e eType; }; class COperatorToken : public CToken { public: // Sub class specific stuff }; class CLiteralToken : public CToken { public: // Sub class specific stuff };And then
vector<CToken *> aTokens; //... for( size_t nI = 0, nMaxI = aTokens.size(); nI < nMaxI; ++nI ) { switch( aTokens[ nI ]->eType ) { case E_OPERATOR : // Do something with sub-class specific stuff. break; case E_LITERAL : // Do something with sub-class specific stuff. break; } }Is it a bad practice ?
Thank you :)
EDIT:
Say i'm analyzing my token list. At some point i'll want to check if the current token is an operator using, as people suggest, a virtual function virtual bool isOperator().Now if it IS an operator, i will want to access that sub class specific stuff to find out, for example, which type of operator it is. In that case, what can i do ? I can't add a method getOperatorType() in my base class, that wouldn't make sense. Is there another way than casting to subclass to retrieve that sub class member value ?
解决方案A type-field really defeats the object orientated nature of C++. Normally you can solve this with polymorphism:
In CToken define a function virtual doSomething(), with appropriate arguments and return type.
Implement that function in COperatorToken and CLiteralToken.
The runtime will call the appropriate function if you then use aTokens[ nI ]->doSomething();
这篇关于C ++ - 好的还是坏的做法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!