im试图构建一个电路模拟器,但遇到了一些固有错误。我想我只是很困惑,因为我盯着它看太久了,所以我很感激你的帮助。
错误消息:
prep_3.cpp: In constructor 'wire::wire(bool&, binary_gate&)':
prep_3.cpp:147:70: error: no matching function for call to 'binary_gate::binary_gate()'
wire(bool &from, binary_gate &to) : bit_output(from), gate_input(to) {
^
类引发问题:
class wire{
public :
wire(binary_gate &from, binary_gate &to) : gate_output(from), gate_input(to) {
//want to pass output of from into to.
//therefore must set_next_bit of to taking the input as the output of from
to.set_next_bit(from.get_output());
}
wire(bool &from, binary_gate &to) : bit_output(from), gate_input(to) {
to.set_next_bit(from);
}
private :
binary_gate gate_output, gate_input;
bool bit_output, bit_input;
};
二进制门类别:
class binary_gate : public logic_element{
public :
binary_gate(string s) : logic_element(s), bitA_status(false), bitB_status(false){};
bool get_bitA(){
if(!bitA_status){
cout << "A hasn't been assigned yet! please set it : " ;
cin >> bitA;
bitA_status = true;
}
return bitA;
}
bool get_bitB(){
if(!bitB_status){
cout << "B hasn't been assigned yet! please set it : " ;
cin >> bitB;
bitB_status = true;
}
return bitB;
}
void set_bitA(bool val){
bitA = val;
bitA_status = true;
}
void set_bitB(bool val){
bitB = val;
bitB_status = true;
}
bool get_statusA(){
return bitA_status;
}
bool get_statusB(){
return bitB_status;
}
virtual void set_next_bit(bool from_bit){
if(!bitA_status){
bitA = from_bit;
this->bitA_status = true;
}
else if(!bitB_status){
bitB = from_bit;
this->bitB_status = true;
}
}
protected:
bool bitA;
bool bitB;
bool bitA_status; // true = taken, false = empty
bool bitB_status; // true = taken, false = empty
};
请记住,在我为wire添加第二个构造函数之前,代码就已经工作了,该构造函数接受了一个bool和一个binary_gate。
我推断错误来自wire类中的第二个构造函数。这让我很困惑,因为它与第一个构造函数非常相似,我所做的只是传递一个bool输入,可以说它应该更容易编码!
感谢
wire
类有4个成员变量。其中的每一个都需要在CCD_ 2的构建过程中进行构建。
wire(bool &from, binary_gate &to) : bit_output(from), gate_input(to)
给出了如何构建bit_output
和gate_input
而不是bit_input
和gate_output
的说明。将为这些调用默认构造函数。但是您没有gate_input
的默认构造函数,它的类型是binary_gate
。
在binary_gate
类中为binary_gate
声明一个公共默认构造函数
binary_gate() = default;
或
binary_gate() : ...initialization list... {}
如果希望默认binary_gate
具有其他特定值。
问题是wire
类的第二个构造函数:
wire(bool &from, binary_gate &to) : bit_output(from), gate_input(to) {
to.set_next_bit(from);
}
需要为binary_gate
调用默认构造函数,为gate_output
成员调用。。。并且您还没有提供默认的构造函数(即没有参数的构造函数(。这是因为,一旦为构造函数提供了不同的签名(如binary_gate(string s)
(,编译器就不再提供隐式默认值。来自cppreference(粗体矿(:
如果没有为类类型(结构、类或联合(提供任何类型的用户声明构造函数,编译器将始终声明默认构造函数作为其类的内联公共成员。
但是,wire
类的另一个构造函数对gate_input
和gate_output
都使用复制构造函数,并且编译器确实为此提供了默认值。同样,来自cppreference:
如果没有为类类型提供用户定义的复制构造函数(结构、类或联合(,编译器将始终声明一个副本构造函数作为其类的非显式内联公共成员。
要绕过这一点,您需要显式设置默认构造函数(无参数(;最简单的方法如下:
class binary_gate : public logic_element{
public :
binary_gate(string s) : logic_element(s), bitA_status(false), bitB_status(false){};
binary_gate() = default; // Provide an *explicit* default constructor.
//...
请随时要求进一步澄清和/或解释。