为什么不使用“foo f();”调用类“foo”的构造函数?
可能的重复:
为什么使用空括号调用不带参数的构造函数会出错?
我遇到了以下问题。我创建了 2 个 foo 实例。 然后我意识到, foo f();
没有执行类的构造函数。这是为什么?
class foo{
public:
foo() {cout <<"executed contructor...";}
};
int main() {
foo f(); // doesn't run the ctor???? why?
foo f2; // this one does execute the ctor
system("pause");
return 0;
}
Possible Duplicate:
Why is it an error to use an empty set of brackets to call a constructor with no arguments?
I bumped into the following problem. I created 2 instances of foo.
Then I realized, that foo f();
didn't execute the contructor of a class. Why is that?
class foo{
public:
foo() {cout <<"executed contructor...";}
};
int main() {
foo f(); // doesn't run the ctor???? why?
foo f2; // this one does execute the ctor
system("pause");
return 0;
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
第一个声明一个函数。尝试访问名为
f
的对象。编译器会抱怨:f 具有非类类型foo ()
,这意味着它是一个不带参数并返回foo
类型的对象的函数。The first declares a function. Try to access the object named
f
. The compiler will complain along the lines: f has non class typefoo ()
, which means it is a function taking no arguments and returning an object of typefoo
.检查 C++ 常见问题解答问题 10.2:
http://www.parashift.com/c++-faq-lite /ctors.html#faq-10.2
Check C++ FAQ question 10.2:
http://www.parashift.com/c++-faq-lite/ctors.html#faq-10.2