Does compiler create default constructor when we write our own?

本文详细解释了C++中默认构造函数的行为。当类没有定义任何构造函数时,编译器会自动生成一个默认构造函数;然而,一旦程序员为类定义了一个构造函数,即使是带有参数的构造函数,编译器也不会再生成默认构造函数。通过两个示例程序对比展示了这一特性。

  

  In C++, compiler by default creates default constructor for every class. But, if we define our own constructor, compiler doesn’t create the default constructor.

  For example, program 1 compiles without any error, but compilation of program 2 fails with error “no matching function for call to `myInteger::myInteger()’ ”

  Program 1

 1 #include<iostream>
 2  
 3 using namespace std;
 4  
 5 class myInteger
 6 {
 7    private:
 8      int value;
 9       
10      //...other things in class  
11 };
12  
13 int main()
14 {
15   myInteger I1;
16   getchar();
17   return 0;
18 }

 


  Program 2

 1 #include<iostream>
 2  
 3 using namespace std;
 4  
 5 class myInteger
 6 {
 7    private:
 8      int value;
 9    public: 
10      myInteger(int v)  // parametrized constructor
11      {  value = v;  }
12     
13      //...other things in class  
14 };
15  
16 int main()
17 {
18   myInteger I1;
19   getchar();
20   return 0;
21 }

 

 

  Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.

  转载请注明:http://www.cnblogs.com/iloveyouforever/

  2013-11-26  10:11:05

转载于:https://www.cnblogs.com/iloveyouforever/p/3442742.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值