我想写一个基于Java代码的c++1z程序
首先在Java中声明一个接口。
public interface MyExpression {
public boolean interpret();
}
java中实现接口的抽象类
public abstract class NonTerminal implements MyExpression {
protected MyExpression left, right;
public void setLeft(MyExpression left) {
this.left = left;
}
public void setRight(MyExpression right) {
this.right = right;
}
}
最后是班级
public class Or extends NonTerminal {
public boolean interpret() {
return left.interpret() || right.interpret();
}
public String toString() {
return String.format("(%s | %s)", left, right);
}
}
如何在现代 C++ 中创建此功能?
更新 C++ 代码片段
#include <iostream>
#include <memory>
#include <ostream>
class BooleanExpression {
public:
virtual ~BooleanExpression() = default;
virtual bool interpret() = 0;
};
class NonTerminal : public BooleanExpression {
protected:
std::unique_ptr<BooleanExpression> left, right;
public:
void setLeft(std::unique_ptr<BooleanExpression>&& left) {
this->left = std::move(left);
}
void setRight(std::unique_ptr<BooleanExpression>&& right) {
this->right = std::move(right);
}
};
class Terminal : public BooleanExpression {
protected:
bool value;
public:
Terminal(bool value) : value(value) {}
//tostring
};
class False : public Terminal {
public:
False() : Terminal(false) {}
//tostring
};
class True : public Terminal {
public:
True() : Terminal(true) {}
//tostring
};
class Or : public NonTerminal {
public:
bool interpret() {
return left->interpret() || right->interpret();
}
};
class And : public NonTerminal {
public:
bool interpret() {
return left->interpret() && right->interpret();
}
//tostring
};
int main() {
using namespace std;
auto t1 = make_unique<True>();
auto f1 = make_unique<False>();
auto or1 = make_unique<Or>();
or1->setLeft(t1);
return 0;
}
这段代码无法编译。or1->setLeft不接受t1,即make_unique()。
白衣染霜花
慕盖茨4494581
相关分类