默认构造函数是什么概念?
通过示例帮助我了解默认构造函数的概念。 我不知道何时在程序中使用默认构造函数,何时不使用。 帮我解决这个问题。用一个例子来解释一下。 什么时候需要使用它?
#include<iostream>
using namespace std;
class abc
{
public:
abc()
{
cout<<"hello";
}
};
int main()
{
abc a;
system("pause");
return 0;
}
那么实际上默认构造函数有什么用以及什么时候需要使用它呢?
help me in getting the concept of default constructor with example.
i don't know when to use default constructor in the program and when not to.
help me coming over this problem.explain it with an example for me.
when it is necessary to use it?
#include<iostream>
using namespace std;
class abc
{
public:
abc()
{
cout<<"hello";
}
};
int main()
{
abc a;
system("pause");
return 0;
}
so actually what is the use of default constructor and when it is necessary to use it?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
符合
DefaultConstrutible
概念的类允许使用以下表达式(N3242 第 17.6.3.1 段):这个概念就这么多了。第 12.1/5 段实际上告诉我们什么是默认构造函数
随着删除的特殊成员函数的引入,该标准还定义了一系列没有隐式默认构造函数可用的情况以及平凡和非平凡默认构造函数的区别。
A class that conforms to the concept
DefaultConstrutible
allows the following expressions (paragraph 17.6.3.1 of N3242):So much for the concept. Paragraph 12.1/5 actually tells us what a default constructor is
With the introduction of deleted special member functions, the standard also defines a list of cases where no implicit default constructor is available and the distinction of trivial and non-trivial default constructors.
如果您的类实例化时不需要执行任何操作。使用默认构造函数,否则在任何情况下您都必须使用自己的构造函数,因为默认构造函数基本上不执行任何操作。
您也不需要编写任何“默认”构造函数。
If you don't need to do anything as your class is instantiated. Use the default constructor, any situation else you will have to use your own constructor as the default constructor basically does nothing.
You also don't need to write any "default" constructor.
new
表达式或初始化表达式调用构造函数。它不能被称为“手动”。成员初始值设定项列表
。检查这个。
new
expression or an initialization expression. It cannot be called "manually".member initializer list
.Check this.
默认构造函数是不带参数的构造函数,将在以下情况下调用:
在不带任何构造函数的情况下实例化或新建类的对象,例如:
<前><代码>abc a;
abc* aptr=新 abc;
声明类的数组,例如:
当您有一个不调用基类构造函数之一的继承类时
当你使用一些标准库的容器如vector时,例如:
在这些情况下你必须有一个默认的构造函数,否则如果你没有任何构造函数,编译器将隐式默认没有任何操作的构造函数,如果你有一些构造函数,编译器会显示编译错误。
如果您想要执行上述操作之一,请使用默认构造函数来确保每个对象都被正确实例化。
Default constructor is constructor with no argument and will be called on these situations:
Instancing or newing an object of a class without any constructor, like:
Declaring an array of a class, like:
When you have a inherited class which does not call one of base class constructors
When you use some containers of standard library such as vector, for example:
In these situations you have to have a default constructor, otherwise if you do not have any constructor, the compiler will make an implicit default constructor with no operation, and if you have some constructors the compiler will show you a compile error.
If you want to do one of the above things, use a default constructor to make sure every object is being instantiated correctly.