C ++ if()进入switch和case语句

时间:2017-02-25 05:21:43

标签: c++

我有三元运算符的if()函数(':','?')

if(operation == ':')
....
....
   if(operation == '?')
....
   return new ternaryOperator(first, second, third)

这些给出了完美的操作价值。但我需要制作它们 Switch()和Case语句。我也使用了Switch()和嵌套的Switch()语句,但它没有返回正确的值。 如何将这些函数放入Switch和Case语句?

#include <iostream>
using namespace std;
#include "expression.h"
#include "subexpression.h"
#include "operand.h"
#include "plus.h"
#include "minus.h"
#include "times.h"
#include "divide.h"
#include "greaterThan.h"
#include "lessThan.h"
#include "equal.h"
#include "and.h"
#include "or.h"
#include "notEqual.h"
#include "ternaryOperator.h"

SubExpression::SubExpression(Expression* left, Expression* right){
   this->left = left;
   this->right = right;
}

SubExpression::SubExpression(Expression* first, Expression* second, Expression* third)
{
   this->first = first;
   this->second = second;
   this->third = third;
}

SubExpression::SubExpression(Expression* left)
{
   this->left = left;
}

Expression* SubExpression::parse()
{
   Expression* left;
   Expression* right;
   Expression* first;
   Expression* second;
   Expression* third;
   char operation, paren;
   bool isTernary = false;

   left = Operand::parse();
   cin >> operation;
   right = Operand::parse();

   **if (operation == ':')
   {
      first = left;
      second = right;
      left = Operand::parse();
      cin >> operation;
      right = Operand::parse();
      if (operation == '?')
      {
         third = right;
         isTernary = true;
      }
   }

   cin >> paren;

   if (isTernary == true)
   {
      return new ternaryOperator(first, second, third);
   }**

   switch (operation)
   {

      case '+':
         return new Plus(left, right);
      case '-':
         return new Minus(left, right);
      case '*':
         return new Times(left, right);
      case '/':
         return new Divide(left, right);
      case '>':
         return new greaterThan(left, right);
      case '<':
         return new lessThan(left, right);
      case '=':
         return new Equal(left, right);
      case '&':
         return new And(left, right);
      case '|':
         return new Or(left, right);

      case '!':
         return new notEqual(left);
   }
   return 0;
}



class ternaryOperator: public SubExpression
{
   public:
      ternaryOperator(Expression* first, Expression* second, Expression* third):
            SubExpression(first, second, third)
   {
   }
      double evaluate()
      {
         return third->evaluate() ? first->evaluate() : second->evaluate();
      }
};

1 个答案:

答案 0 :(得分:0)

确定。我能够将嵌套的if(operation =='?')分解为下面的Switch和case语句,并且它有效。 但我仍然需要将主if(operation ==':')放入switch和case语句

if (operation == ':')
    {
        first = left;
        second = right;
        left = Operand::parse();
        cin >> operation;
        right = Operand::parse();}
..
...
....
case '?':
    third = right;
    return new ternaryOperator(first, second, third);