C++测试程序(1)——测试C++对象作为函数参数和返回值的内存分配

一直使用C,由于项目需要,学习一些C++作为补充。由于开始的习惯,拿着对象都是指针进,指针出,虽然没有多少问题,但经常还是感觉别扭。网上找了找,没有看见写的特别清楚和完全的(可能比较分散),这里写个测试程序辅助理解。

测试程序如下:

#include  < iostream >

using   namespace  std;

class  Test
{
public:
    Test(
int x, int y)
    
{
        x_ 
= x;
        y_ 
= y;
    }


    
~Test()
    
{
    }

    
    
void out()
    
{
        cout 
<< " " << &x_ << " " << x_ << endl;
    }

    
    template 
<class T> void out(T msg)
    
{
        cout 
<< " " << msg << " " << &x_ << " " << x_ << endl;
    }

    
    
void setX(int x)
    
{
        x_ 
= x;
    }


private:
    
int x_;
    
int y_;

}
;

Test test1(Test t)
{
    t.
out(__LINE__);
    t.setX(
1);
    
return t;
}


Test
&  test2(Test &  t)
{
    t.
out(__LINE__);
    t.setX(
2);
    
return t;
}


Test test3(Test
&  t)
{
    t.
out(__LINE__);
    t.setX(
3);
    
return t;
}


Test
&  test4(Test t)
{
    t.
out(__LINE__);
    
return t;
}


int  main()
{
    Test t 
= Test(00);
    t.
out(__LINE__);
    cout 
<< "test1:" << endl;
    test1(t).
out(__LINE__);
    Test t1
=test1(t);
    t1.
out(__LINE__);
    cout 
<< "test2:" << endl;
    test2(t).
out(__LINE__);
    Test
& t2=test2(t);
    t2.
out(__LINE__);
    cout 
<< "test3:" << endl;
    test3(t).
out(__LINE__);
    Test t3
=test3(t);
    t3.
out(__LINE__);
    cout 
<< "test4:" << endl;
    test4(t).
out(__LINE__);
    Test
& t4=test4(t);
    t4.
out(__LINE__);
    t1.
out();
    t2.
out();
    t3.
out();
    t4.
out();
}

测试结果(mingw,gcc):

 69 0x22ff50 0
test1:
 41 0x22ff30 0
 71 0x22ff40 1
 41 0x22ff40 0
 73 0x22ff30 1
test2:
 48 0x22ff50 0
 75 0x22ff50 2
 48 0x22ff50 2
 77 0x22ff50 2
test3:
 55 0x22ff50 2
 79 0x22ff40 3
 55 0x22ff50 3
 81 0x22ff40 3
test4:
 62 0x22ff10 3
 83 0x22ff10 3
 62 0x22ff10 3
 85 0x22ff10 3
 0x22ff30 1
 0x22ff50 3
 0x22ff40 3
 0x22ff10 3

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值