简体   繁体   English

计算表达式二叉树C ++

[英]evaluate expression binary tree c++

I was trying to learn this implementation of a binary tree that evaluates an expression. 我正在尝试学习这种对表达式进行评估的二叉树的实现。 I was unable to run it and see the output. 我无法运行它并查看输出。 How would i get 3*(7+1)/4+(17-5), which results in 18. Here is the link http://math.hws.edu/eck/cs225/s03/binary_trees/ 我将如何获得3 *(7 + 1)/ 4 +(17-5),结果为18。这是链接http://math.hws.edu/eck/cs225/s03/binary_trees/

class ExpNode {
          // Represents a node of any type in an expression tree.
          // This is an "abstract" class, since it contains an undefined
          // function, value(), that must be defined in subclasses.
          // The word "virtual" says that the defintion can change
          // in a subclass.  The "= 0" says that this function has
          // no definition in this class.

     public:     

       virtual double value() = 0;  // Return the value of this node.

   }; // end class ExpNode


class ConstNode : public ExpNode {
          // Represents a node that holds a number.  (The
          // ": public ExpNode" says that this class is
          // a subclass of ExpNode.)

       double number;  // The number in the node.

     public:

       ConstNode( double val ) {
             // Constructor.  Create a node to hold val.
          number = val;
       }

       double value() {
             // The value is just the number that the node holds.
          return number;
       }

    }; // end class ConstNode


class BinOpNode : public ExpNode {
          // Represents a node that holds an operator.

       char op;        // The operator.
       ExpNode *left;   // The left operand.
       ExpNode *right;  // The right operand.

     public:

       BinOpNode( char op, ExpNode *left, ExpNode *right ) {
             // Constructor.  Create a node to hold the given data.
          this->op = op;
          this->left = left;
          this->right = right;
       }

       double value() {
             // To get the value, compute the value of the left and
             // right operands, and combine them with the operator.
           double leftVal = left->value();
           double rightVal = right->value();
           switch ( op ) {
               case '+':  return leftVal + rightVal;
               case '-':  return leftVal - rightVal;
               case '*':  return leftVal * rightVal;
               case '/':  return leftVal / rightVal;
            }
       }

    }; // end class BinOpNode

Here is my attempt to make a main function: 这是我尝试做的主要功能:

int main() {
    BinOpNode *opnode;
    opnode = new BinOpNode;
    opnode->value()=5;
    ExpNode *expnode;
    expnode = opnode;
    expnode->value();
    return 0;

}

It does not compile, this is the errors 它不编译,这是错误

15:58:27 **** Incremental Build of configuration Debug for project ExpNode ****
Info: Internal Builder is used for build
g++ -O0 -g3 -Wall -c -fmessage-length=0 -o "src\\ExpNode.o" "..\\src\\ExpNode.cpp" 
..\src\ExpNode.cpp: In function 'int main()':
..\src\ExpNode.cpp:60:15: error: no matching function for call to 'BinOpNode::BinOpNode()'
..\src\ExpNode.cpp:36:2: note: candidates are: BinOpNode::BinOpNode(char, ExpNode*, ExpNode*)
..\src\ExpNode.cpp:30:33: note:                 BinOpNode::BinOpNode(const BinOpNode&)
..\src\ExpNode.cpp:61:18: error: lvalue required as left operand of assignment

15:58:28 Build Finished (took 405ms)

None of the classes have default constructors. 没有一个类具有默认构造函数。
value returns the result of evaluating the expression, and you need to pass the necessary parts of an expression as its parameters when it's constructed. value返回评估表达式的结果,并且在构造表达式时,需要将表达式的必要部分作为其参数传递。
(It's unclear how you would expect to be able to assign the value 5 to a binary expression.) (尚不清楚如何期望将值5分配给二进制表达式。)

You need to build a tree from the leaves (which will be constants) up towards the root. 您需要从叶子(将是常量)到根部构建一棵树。
As an example, here's the expression 5 + 3 : 例如,这是表达式5 + 3

ConstNode five(5);
ConstNode three(3);
BinOpNode fiveplusthree('+', &five, &three);
std::cout << fiveplusthree.value(); // Should print 8

I think the problem is in your main() function's logic. 我认为问题出在您的main()函数的逻辑中。

According to the definition of the given classes, first you should create an object of type ConstNode for each number in the expression. 根据给定类的定义,首先应为表达式中的每个数字创建一个类型为ConstNode的对象。 Then, you should create BinOpNode for each operator in the expression. 然后,您应该为表达式中的每个运算符创建BinOpNode

And by the way, that expression evaluates to 18, not 82! 顺便说一下,该表达式的值为18,而不是82!

Something like this: 像这样:

//3*(7+1)/4+(17-5)  = 18
int main()
{
  BinOpNode *a, *b;
  a = new BinOpNode('+', new ConstNode(7), new ConstNode(1));
  a = new BinOpNode('*', new ConstNode(3), a);
  a = new BinOpNode('/', a, new ConstNode(4));
  b = new BinOpNode('-', new ConstNode(17), new ConstNode(5));
  b = new BinOpNode('+', a, b);
  cout << b->value();
}

PS: We can pass an object of class ConstNode when an object of ExpNode is expected in the constructor of BinOpNode as ConstNode inherits from ExpNode abstract base class. PS:当ExpNode的构造函数中需要BinOpNode的对象时,我们可以传递ConstNode类的对象,因为ConstNode继承自ExpNode抽象基类。

In C++, default constructors work interestingly. 在C ++中,默认构造函数的工作有趣。

If you don't define any constructors, a default constructor is generated for you: 如果您未定义任何构造函数,则会为您生成一个默认构造函数:

class A {};

int main()
{
    A a; // perfectly fine

But if you define any other constructor, those generated constructors go away: 但是,如果定义任何其他构造函数,这些生成的构造函数就会消失:

class A
{
    A(int) { ... }
};

int main()
{
    A a; // ERROR!
}

In this scenario, the default constructor doesn't exist because you defined one, and the compiler didn't generate one for you. 在这种情况下,默认构造函数不存在,因为您定义了一个构造函数,并且编译器没有为您生成一个。

This is your problem because here in main , you have this line: 这是您的问题,因为在main ,您有以下一行:

opnode = new BinOpNode;

which runs the default constructor of BinOpNode . 运行默认的BinOpNode构造BinOpNode Look at your BinOpNode constructors: 查看您的BinOpNode构造函数:

BinOpNode( char op, ExpNode *left, ExpNode *right )

Hey look: thats not a default constructor! 嘿,这不是默认的构造函数!

You have two options: either add a default constructor to the class: 您有两个选择:向该类添加默认构造函数:

BinOpNode() { ... }

or use the arguments when calling new : 或在调用new时使用参数:

opnode = new BinOpNode(op, left, right);

Good Luck! 祝好运!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM