2008年10月31号——c++重载构造函数

  1. #include<iostream>
  2. using namespace std;
  3. class myclass{
  4.     public:
  5.     int *p;
  6.     int a;
  7.     myclass(int *fp,int x){
  8.         cout<<" constructor "<<endl;
  9.         a=x;
  10.         p=fp;
  11.     }
  12.     myclass(const myclass &b){
  13.         cout<<" copy-struct"<<endl;
  14.         a=2*b.a;
  15.         system("pause");
  16.     }
  17.     ~myclass(){
  18.         cout<<" destruct"<<endl;
  19.         
  20.     }
  21. };
  22. myclass f(myclass y)//myclass y(t)
  23. {
  24.     cout<<"-------------in f(y)--------------------"<<endl;
  25.     cout<<"&y="<<&y<<endl;
  26.     cout<<" y.a++="<<y.a++<<"/n"<<endl;
  27.     return y;//copy-construct   
  28. }
  29. myclass addf(myclass &y)//myclass &y=t;
  30. {
  31.     cout<<"-------------in addf(&y)----------------"<<endl;
  32.     cout<<"&Y:  "<<&y<<endl;
  33.     cout<<" y.a++="<<y.a++<<"/n"<<endl;
  34.     return y;//copy-construct   
  35. }
  36. int main()
  37. {
  38.     int x=0;
  39.     myclass t(&x,2);
  40.     
  41.     cout<<"after creat t(2)"<<endl;
  42.     cout<<"&t="<<&t<<endl;
  43.     cout<<"f(t).a=  "<<f(t).a<<endl;
  44.     
  45.     cout<<"AFTER F(T), NEXT IS ADDF(&T)"<<endl;
  46.     cout<<"right know/n    t(2)="<<t.a<<"/n"<<endl;
  47.     
  48.     cout<<"addf(&t).a=  "<<addf(t).a<<endl;
  49.     cout <<"before end of main"<<"  t(2)="<<t.a<<endl;
  50.     system("pause");
  51. }

 

构造函数,用来给类赋初值,还有一种特殊的构造函数,叫拷贝构造函数,进行对象初始化,当对象以值传递方式掉入函数f(myclass),或者以值传递方式返回 如return myclass,都会调用拷贝构造函数,如上程序,拷贝构造函数使原对象乘2,这样在调用和返回时会使对象各乘2,但是如果没有显示定义拷贝构造函数那么在调用时编译器会默认一个为拷贝,实际上在传入和返回时都开辟了空间,通过拷贝构造函数开辟空间。

资料:http://zhidao.baidu.com/question/7513262.html

函数结果:图片

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值