为什么缺省构造函数在某些情况下不可用 [英] why default constructor is not available by default in some case

查看:203
本文介绍了为什么缺省构造函数在某些情况下不可用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

class foo {
public:
   int a;
   int b;
   foo(int a_, int b_) : a(a_), b(b_) {}
};

int main() {
  foo f;
}

当我尝试编译上述代码片段时, :

when I try to compile the above code snippet, I got error message as below:

foo.cc: In function 'int main()'

foo.cc:12: error: no matching function for call to 'main()::foo::foo()'

foo.cc:10: note: candidates are: main()::foo::foo(int, int)

foo.cc:6:  note:                 main()::foo::foo(const main()::foo&)

但是如果我用两个整数prarmeters注释显式构造函数的文件,那么
可以编译代码。我猜想的魔法背后的规则是,当你解释
声明具有参数的构造函数时,c ++ compilor不会自动生成一个没有参数的
默认构造函数。

but if I comment the file of explicit constructor with two integer prarmeters, then the code can be compiled. I guess the rule behind the magic is that when you explicite declare constructor with parameters, c++ compilor will not atuomatically generate a default constructor with no parameters for you.

我是对的吗?如果是对的,为什么c ++有这样的行为?提前感谢。

Am I right? If am right, why does c++ has such behaviour? thanks in advance.

推荐答案

只有没有用户定义的构造函数,编译器才会生成默认构造函数。

Compiler generates default constructor only if there're no user defined constructors.

C ++ Standard 12.1 / 5:

C++ Standard 12.1/5:


类X的默认构造函数是类X的构造函数可以不带参数调用。如果
没有用户声明的类X的构造函数,则隐式声明一个默认构造函数。

A default constructor for a class X is a constructor of class X that can be called without an argument. If there is no user-declared constructor for class X, a default constructor is implicitly declared.

这篇关于为什么缺省构造函数在某些情况下不可用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆