C++ 调用默认构造函数
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/5300124/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
calling the default constructor
提问by Vijay
class base {
int i;
public:
base()
{
i = 10;
cout << "in the constructor" << endl;
}
};
int main()
{
base a;// here is the point of doubt
getch();
}
What is the difference between base a
and base a()
?
base a
和 和有base a()
什么区别?
in the first case the constructor gets called but not in the second case!
在第一种情况下,构造函数被调用,但在第二种情况下不会!
回答by Bo Persson
The second one is declaring a function a() that returns a base object. :-)
第二个是声明一个返回基对象的函数 a()。:-)
回答by Mark B
base a
declares a variable a
of type base
and calls its default constructor (assuming it's not a builtin type).
base a
声明一个a
类型的变量base
并调用其默认构造函数(假设它不是内置类型)。
base a();
declares a function a
that takes no parameters and returns type base
.
base a();
声明一个a
不带参数并返回 type的函数base
。
The reason for this is because the language basically specifies that in cases of ambiguity like this anything that can be parsed as a function declaration should be so parsed. You can search for "C++ most vexing parse" for an even more complicated situation.
这样做的原因是因为语言基本上规定,在这样的歧义的情况下,任何可以解析为函数声明的东西都应该被解析。对于更复杂的情况,您可以搜索“C++ most vexing parse”。
Because of this I actually prefer new X;
over new X();
because it's consistent with the non-new declaration.
因此,我实际上更喜欢它new X;
,new X();
因为它与非新声明一致。
回答by M'vy
In C++, you can create object in two way:
在 C++ 中,您可以通过两种方式创建对象:
- Automatic (static)
- Dynamic
- 自动(静态)
- 动态的
The first one uses the following declaration :
第一个使用以下声明:
base a; //Uses the default constructor
base b(xxx); //Uses a object defined constructor
The object is deleted as soon as it get out of the current scope.
对象一旦离开当前范围就会被删除。
The dynamic version uses pointer, and you have the charge to delete it :
动态版本使用指针,您有责任删除它:
base *a = new base(); //Creates pointer with default constructor
base *b = new base(xxx); //Creates pointer with object defined constructor
delete a; delete b;