c++ 中的对象声明和定义
可能的重复:
在类型名称后面添加括号与 new 有区别吗?
我看到有人使用这样的构造函数:
class Foo
{
public: Foo();
};
int main(){
Foo *f= new Foo;
}
Foo *f= new Foo;
和 Foo *f= new Foo(); 之间有什么区别? ?
Possible Duplicate:
Do the parentheses after the type name make a difference with new?
I saw someone uses the constructor like this:
class Foo
{
public: Foo();
};
int main(){
Foo *f= new Foo;
}
what is the difference between Foo *f= new Foo;
and Foo *f= new Foo();
?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
这两种形式的初始化之间没有区别。假设构造函数是
public
,两者都会调用默认构造函数。There is no difference between those two forms of initializations. Both will call the default constructor, given that the constructor is
public
.首先,您给出的代码将无法编译。您需要
Foo* f = new Foo()
注意星号。
否则,对于非基本类型,这两个调用具有相同的结果。我曾在一些公司工作过,其中 () 语法是由样式指南强制执行的,并且有一个很好的理由:对于原始类型可能存在差异:
这里可能很明显,但想象一下 Foo 是一个 typedef。所以我的建议是:始终使用 Foo() 语法。
First of all the code you give will not compile. You need to have
Foo* f = new Foo()
Notice the asterisk.
Otherwise the two calls have the same result for non-primitive types. I have worked in companies where the () syntax is enforced by the styleguide and for a good reason: for primitive types there can be a difference:
It may be obvious here but imagine that Foo is a typedef for instance. So my advice is: always use the Foo() syntax.
我们的示例甚至可能无法编译,您需要声明一个指针
,并且键入
new Foo
或new Foo()
没有区别,因为两者都运行构造函数,而没有论据。Ỳour example probably even won't compile, you need to declare a pointer
and there is no difference in typing
new Foo
ornew Foo()
since both run the constructor with no arguments.