我試圖學習評估表達式的二叉樹的實現。我無法運行它並查看輸出。我怎麼會得到3 *(7 + 1)/ 4 +(17-5),這將導致18 這裏是鏈接http://math.hws.edu/eck/cs225/s03/binary_trees/評估表達式二叉樹C++
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
這是我試圖做一個主要功能:
int main() {
BinOpNode *opnode;
opnode = new BinOpNode;
opnode->value()=5;
ExpNode *expnode;
expnode = opnode;
expnode->value();
return 0;
}
它不能編譯,這是錯誤
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)
你怎麼*無法運行它,看到輸出*?它沒有編譯?如果沒有,你應該發佈編譯器錯誤。 – NathanOliver
我剛編輯! – sm15
@ sm15您正在構造一個沒有參數的'BinOpNode'對象:'opnode = new BinOpNode;'。看看你的'BinOpNode'類。你看到沒有這樣的構造函數沒有任何參數。這正是錯誤告訴你的。 – PaulMcKenzie