构造函数采用 Base&不被调用
Constructor taking Base& is not called
我正在为布尔代数编写一个简单的程序,但双否定并不能按预期工作。
我有以下课程:
操作员:
#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
。复制构造函数的签名匹配得更好,因此被选中。
相关文章:
- 构造函数采用 Base&不被调用
- 从 Base 引用对象调用派生类的成员
- 如何在派生类中不显式调用base::func()的情况下从基类执行虚拟函数
- 派生对象调用的 Base 方法的模板推导
- 使用 static_cast、dynamic_cast 或显式转换进行派生指向 Base 指针转换的指针不会调用 base 函数
- 我如何调用基类的虚拟函数定义,这些定义在Ampract Base类和C 中的派生类中都有定义
- 为什么当派生类调用 base 的纯虚函数时 g++ 不抱怨?
- 在不手动键入base::method()的情况下,我可以递归地调用每个基中的方法吗
- 正在调用派生方法而不是Base
- 让 foo(derived_object) 调用 foo(Base const&) 而不是模板函数?
- 这是正确的吗:在构造 Base 对象之前调用了派生的虚拟方法
- 调用 ~Derived() 和 ~Base() 之间的对象状态
- C++错误,显示创建链接列表调用"error LinkedList Interface is an inaccessable base of linkedlist"
- 如何在创建新的 obj() 时调用基类构造函数 new base(argT argV)
- 从 base 的特定派生类型调用特定函数
- 使用 "new" 为派生类分配内存时,如何调用 Base 构造函数?
- 在Python中继承c++的Base,使用SWIG调用抽象方法
- 为什么派生类的函数在 PHP 中没有通过 base 调用?
- C++:从派生实例调用 base 中的纯虚拟方法重载
- 多重继承派生类:如何在不重复调用 base 的情况下重用派生函数