加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

c – 默认情况下,默认构造函数在某些情况下不可用

发布时间:2020-12-16 10:27:48 所属栏目:百科 来源:网络整理
导读:class foo {public: int a; int b; foo(int a_,int b_) : a(a_),b(b_) {}};int main() { foo f;} 当我尝试编译上面的代码片段时,我收到如下错误消息: foo.cc: In function 'int main()'foo.cc:12: error: no matching function for call to 'main()::foo::f
class foo {
public:
   int a;
   int b;
   foo(int a_,int b_) : a(a_),b(b_) {}
};

int main() {
  foo f;
}

当我尝试编译上面的代码片段时,我收到如下错误消息:

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不会自动生成一个
没有参数的默认构造函数.

我对吗?如果对,为什么c有这种行为?提前致谢.

解决方法

仅当没有用户定义的构造函数时,编译器才会生成默认构造函数.

C标准12.1 / 5:

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.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读