默认构造函数 C++错误
我需要班级建设方面的帮助。在我的课程中,我使用了复制构造函数和运算符=来防止编译器创建它们。在我的主程序中,当我尝试创建该类的实例时,收到一条错误消息“该类不存在默认构造函数”。
可能是什么问题?
这是我的代码片段。
class netlist {
netlist(const netlist &);
netlist &operator=(const netlist &);
std::map<std::string, net *> nets_;
}; // class netlist
在我的主要函数中,我使用:
netlist nl;
这是我收到错误的地方。我提供了复制构造函数声明,因此它们不应该成为问题。
我将不胜感激任何帮助。提前致谢。
I require help with respect to class construction. In my class, I have used a copy constructor and operator= to prevent the compiler from creating them. In my main program, when I try to create an instance of the class, I get an error saying "No default constructor exists for the class".
What could be the problem?
This is a snippet of my code.
class netlist {
netlist(const netlist &);
netlist &operator=(const netlist &);
std::map<std::string, net *> nets_;
}; // class netlist
In my main function I am using:
netlist nl;
This is where I get the error. I am providing the copy constructor declaration, so they should not be a problem.
I would appreciate any help with this. Thanks in advance.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
代码有两个问题 -
“我收到一条错误消息“该类不存在默认构造函数”。
因为如果提供任何类型的构造函数作为类声明的一部分(
netlist
类有一个在这种情况下是复制构造函数),编译器不提供默认构造函数(即不带参数的构造函数)。netlist.h
netlist.cpp
There are two problems with the code -
"I get an error saying "No default constructor exists for the class" ".
Because if any kind of constructor is provided as a part of class declaration(
netlist
class has a copy constructor in this case), default constructor( i.e., constructor with no arguments ) is not provided by compiler.netlist.h
netlist.cpp
创建网表时,您没有向构造函数传递任何参数,这意味着您正在调用默认构造函数。但是您没有定义默认构造函数。您仅在此处创建了一个采用不同网表作为参数的构造函数(复制构造函数):
您应该像这样定义默认构造函数:
请注意,如果您没有定义任何构造函数,编译器将添加默认构造函数,但由于您添加了副本构造函数,你必须自己定义它们。
When you create the netlist you are not passing any arguments to the constructor which means you are calling a default constructor. However you didn't define a default constructor. You only created a constructor taking a different netlist as a parameter (the copy constructor) here:
You should define a default constructor like this:
Note that had you not defined any constructor, the compiler would have added default ones but since you added the copy constructor, you have to define all of them yourself.
标准的
[class.ctor]
部分说(草案 n3242 中的措辞):您有一个用户声明的构造函数:
因此编译器不提供默认构造函数。
section
[class.ctor]
of the standard says (wording from draft n3242):You have a user-declared constructor:
thus the compiler does not provide a default constructor.