【发布时间】:2020-07-13 12:01:27
【问题描述】:
我有 3 个类,我希望每个类都以不同的方式打印到终端,我有一个节点类表示 BDD 图中的一个顶点,现在我正在尝试编写代码来执行逻辑操作在节点上。
Node 类是这样设置的:
class Node {
char name;
public:
Node() { name = '0'; }
Node(char c) { name = c; }
Node(const Node& n) { name = n.name; }
friend ostream& operator<<(ostream& stream, const Node& n);
};
ostream& operator<<(ostream& stream, const Node& n) {
return stream << "{ Node " << n.name << " }";
}
操作符类是这样设置的:
class Operation {
public:
Node result;
friend std::ostream& operator<<(std::ostream& stream, const Operation& op);
Operation() {}
Operation(const Operation& op) { cout << "Copying " << *this << endl; }
virtual ~Operation() { cout << "Destroying " << *this << endl; }
virtual Node compute() {
cout << "Computing " << *this << endl;
result = Node('1');
return result;
}
};
std::ostream& operator<<(std::ostream& stream, const Operation& op) {
return stream << "Operation { Unspecified }";
}
class UnaryOperation : public Operation {
public:
Node arg1;
UnaryOperation(const Node& arg1) { this->arg1 = arg1; }
UnaryOperation(const UnaryOperation& op) : Operation::Operation(op) {
arg1 = op.arg1;
}
virtual ~UnaryOperation() {}
friend ostream& operator<<(ostream& stream, const UnaryOperation& op);
};
ostream& operator<<(ostream& stream, const UnaryOperation& op) {
return stream << "Operation { arg1: " << op.arg1 << " }";
}
class BinaryOperation : public UnaryOperation {
public:
Node arg2;
BinaryOperation(const Node& arg1, const Node& arg2) : UnaryOperation(arg1) {
this->arg2 = arg2;
}
BinaryOperation(const BinaryOperation& op) : UnaryOperation::UnaryOperation(op) {
arg2 = op.arg2;
}
virtual ~BinaryOperation() {}
friend ostream& operator<<(ostream& stream, const BinaryOperation& op);
};
ostream& operator<<(ostream& stream, const BinaryOperation& op) {
return stream << "Operation { arg1: " << op.arg1 << ", arg2: " << op.arg2;
}
出于调试原因,这些消息需要打印出来,但是当我运行它时
Node apply(Operation& op) {
cout << "Performing apply operation on " << op << endl;
op.compute();
return op.result;
}
int main() {
Node a('a'), b('b');
UnaryOperation uop(a);
BinaryOperation bop(a, b);
cout << uop << endl;
cout << bop << endl;
apply(uop);
apply(bop);
}
我明白了
Operation { arg1: { Node a } }
Operation { arg1: { Node a }, arg2: { Node b }
Performing apply operation on Operation { Unspecified }
Computing Operation { Unspecified }
Performing apply operation on Operation { Unspecified }
Computing Operation { Unspecified }
Destroying Operation { Unspecified }
Destroying Operation { Unspecified }
不用说,这对调试帮助不大。
为什么会这样,我该如何解决?
【问题讨论】:
-
class UnaryOperation : Operation-- 私有继承? -
对不起,我刚刚忘记了,我已经添加了。
-
查看我最近的编辑
-
这看起来像是您试图使用在析构函数中调用基类构造函数的语法。这不会编译,你也不需要,基类的析构函数会被自动调用。
标签: c++ inheritance operator-overloading virtual friend-function