调用有参构造函数的三种方法

来源:互联网 发布:潮男裤子知乎 编辑:程序博客网 时间:2024/05/22 17:23
[cpp] view plain copy
 print?在CODE上查看代码片派生到我的代码片
  1. #include <iostream>  
  2. using namespace std;  
  3.   
  4. class Test  
  5. {  
  6. public:  
  7.     Test()  
  8.     {  
  9.         m_a = 0;  
  10.         m_b = 0;  
  11.         cout<<"无参构造函数"<<endl;  
  12.     }  
  13.     Test(int a)//3种方法  
  14.     {  
  15.         m_a = a;  
  16.         m_b = 0;  
  17.         cout<<"1个参数有参构造函数"<<endl;  
  18.     }  
  19.     Test(int a, int b )//3种方法  
  20.     {  
  21.         m_a = a;  
  22.         m_b = b;  
  23.         cout<<"有参构造函数"<<endl;  
  24.     }  
  25.     Test(const Test&obj)  
  26.     {  
  27.         cout<<"赋值构造函数"<<endl;  
  28.     }  
  29.     void print()  
  30.     {  
  31.         cout<<m_a<<endl;  
  32.         cout<<"普通函数"<<endl;  
  33.     }  
  34. protected:  
  35. private:  
  36.     int m_a ;  
  37.     int m_b;  
  38. };  
  39. void display()  
  40. {  
  41.     //1.调用有参构造函数方法1  
  42.     //Test t(1,2);  
  43.     //t.print();  
  44.   
  45.     //1.调用有参构造函数方法2  
  46.     //Test t = (1,2,3);//逗号表达式 取最后一个值  
  47.     //t.print();  
  48.   
  49.     //1.调用有参构造函数方法3   
  50.     Test t = Test(1,2);//编译器会产生一个匿名对象  
  51.     //t.print();  
  52. }  
  53. int main()  
  54. {  
  55.     display();  
  56.     system("pause");  
  57.     return 0;  
  58. }  

参考来自:http://blog.csdn.net/bbs375/article/details/52618085

0 0