采用Base的构造函数并未调用

Cor*_*ore 11 c++ inheritance constructor

我正在研究一个布尔代数的简单程序,但双重否定不能按预期工作.

我有以下课程:

运营商:

#ifndef OPERATOR_H
#define OPERATOR_H

class Operator {
public:
    virtual int getArity(void) const = 0;
    virtual bool calc(void) const = 0;
};

#endif // OPERATOR_H
Run Code Online (Sandbox Code Playgroud)

假:

#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
Run Code Online (Sandbox Code Playgroud)

不:

#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
Run Code Online (Sandbox Code Playgroud)

我的main.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;
}
Run Code Online (Sandbox Code Playgroud)

由于d = Not(Not(False()))我希望它是假的.

输出是:

not constructor called
n.calc(): 1
d.calc(): 1 <== should be 0
Run Code Online (Sandbox Code Playgroud)

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

Rei*_*ica 19

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

  • 更多细节:`Not(Operator&child)`不是复制构造函数,尽管它*可以用相同类型的参数调用.隐式定义的拷贝构造函数也存在. (3认同)
  • 作为一种可能的解决方案,您可以使用Operator*child,或使用static_const <Operator&>传递该值.要避免静默复制,可以删除复制构造函数并使用统一初始化语法. (3认同)