构造函数采用 Base&不被调用

Constructor taking Base& is not called

本文关键字:调用 Base 构造函数      更新时间:2023-10-16

我正在为布尔代数编写一个简单的程序,但双否定并不能按预期工作。

我有以下课程:

操作员:

#ifndef OPERATOR_H
#define OPERATOR_H
class Operator {
public:
virtual int getArity(void) const = 0;
virtual bool calc(void) const = 0;
};
#endif // OPERATOR_H

错误:

#ifndef FALSE_H
#define FALSE_H
#include "operator.h"
class False : public Operator {
public:
int getArity() const {
return 0;
}
bool calc(void) const {
return false;
}
};
#endif // FALSE_H

不是:

#ifndef NOT_H
#define NOT_H
#include "operator.h"
class Not : public Operator {
public:
Not(Operator& child) : m_child(child) {
std::cout << "not constructor called" << std::endl;
}
int getArity(void) const {
return 1;
}
bool calc(void) const {
return !m_child.calc();
}
private:
Operator& m_child;
};
#endif // NOT_H

我的主.cpp:

#include <iostream>
#include "operator.h"
#include "not.h"
#include "false.h"
using namespace std;
int main(int argc, char *argv[]) {
False f;
Not n = Not(f);
Not d = Not(n);
cout << "n.calc(): " << n.calc() <<endl;
cout << "d.calc(): " << d.calc() <<endl;
return 0;
}

由于d=Not(Not(False((((,我希望它是False。

输出为:

not constructor called
n.calc(): 1
d.calc(): 1 <== should be 0

为什么类Not的构造函数没有用类型为Not的对象作为子对象进行调用?

Not d = Not(n);调用Not的复制构造函数,因为参数的类型也是Not。复制构造函数的签名匹配得更好,因此被选中。