//Node.h
#ifndef _NODE_H_
#define _NODE_H_
class Node
{
public:
virtual double Calc() const = 0;
virtual ~Node() {};//析构函数声明为虚函数,析构时才会调用派生类析构函数
};
class NumberNode : public Node
{
public:
NumberNode(double number) : number_(number) {}
double Calc() const;//如果不实现,则其也是抽象类
private:
const double number_;
};
class BinaryNode : public Node//抽象类
{
public:
BinaryNode(Node* left, Node* right)
: left_(left), right_(right){}
~BinaryNode();//需要释放left_,right_
protected:
Node* const left_;//指针本身不能改变,不能指向其他节点
Node* const right_;
};
class UnaryNode : public Node
{
public:
UnaryNode(Node* child)
: child_(child){}
~UnaryNode();
protected:
Node* const child_;
};
class AddNode : public BinaryNode
{
public:
AddNode(Node* left, Node* right)
:BinaryNode(left, right){}//调用基类构造函数初始化
double Calc() const;//需要实现
};
class SubNode : public BinaryNode
{
public:
SubNode(Node* left, Node* right)
:BinaryNode(left, right){}//调用基类构造函数初始化
double Calc() const;//需要实现
};
class MultiplyNode : public BinaryNode
{
public:
MultiplyNode(Node* left, Node* right)
:BinaryNode(left, right){}//调用基类构造函数初始化
double Calc() const;//需要实现
};
class DivideNode : public BinaryNode
{
public:
DivideNode(Node* left, Node* right)
:BinaryNode(left, right){}//调用基类构造函数初始化
double Calc() const;//需要实现
};
class UMinusNode : public UnaryNode
{
public:
UMinusNode(Node* child)
:UnaryNode(child){}
double Calc() const;
};
#endif
//Node.cpp
#include "Node.h"
#include <cmath>
#include <iostream>
double NumberNode::Calc() const
{
return number_;
}
BinaryNode::~BinaryNode()
{
delete left_;
delete right_;
}
double AddNode::Calc() const
{
return left_->Calc() + right_->Calc();
}
double SubNode::Calc() const
{
return left_->Calc() - right_->Calc();
}
double MultiplyNode::Calc() const
{
return left_->Calc() * right_->Calc();
}
double DivideNode::Calc() const
{
double divisor = right_->Calc();
if (divisor != 0)
return left_->Calc() / divisor;
else
{
std::cout << "Error: Divisor by zero" << std::endl;
return HUGE_VAL;
}
}
double UMinusNode::Calc() const
{
return -child_->Calc();
}
//main.cpp
#include <iostream>
int main(void)
{
}
40 面向对象版表达式计算器(一)
最新推荐文章于 2021-02-23 17:46:26 发布