C ++ - 好的还是坏的做法? [英] C++ - Good or bad practice?

查看:125
本文介绍了C ++ - 好的还是坏的做法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我遇到的情况,我发现它很方便的存储基类中的对象的类型(作为枚举),进一步将指向该基类的指针转换为子类指针,取决于它的值类型。



例如:

  class CToken 
{
public:
token_type_e eType;
}

class COperatorToken:public CToken
{
public:
// sub class specific stuff
};

class CLiteralToken:public CToken
{
public:
//子类特定的东西
};

然后

  vector< CToken *> aTokens; 

// ...

for(size_t nI = 0,nMaxI = aTokens.size(); nI
switch(aTokens [nI] - > eType)
{
case E_OPERATOR:
//使用子类指定的东西做某事。
break;
case E_LITERAL:
//使用子类指定的东西做一些事情。
break;
}
}

这是不好的做法吗?



谢谢:)



编辑:



说我正在分析我的令牌列表。在某些时候,我想检查当前令牌是否是一个运算符使用,如人们建议的虚拟函数 virtual bool isOperator()
现在如果它是一个操作符,我会想访问那个子类特定的东西来找出,例如,它是哪种类型的操作符。在这种情况下,我能做什么?我不能在我的基类中添加一个方法getOperatorType(),这是没有意义的。有没有另一种方法转换到子类来检索子类成员值?

解决方案

类型字段真的击败面向对象C ++的性质。通常,您可以使用多态性解决此问题:



CToken



中实现该函数COperatorToken / 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 ++ - 好的还是坏的做法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆