C++ 引用新发现

今天在《C++ PRIMER PLUS》上学习模板的时候看到了这样一段代码(简化版):

 

#include<iostream>

#include<cstdio>

#include<cstdlib>

#include<cstring>

using namespace std;

template <class T1,class T2>

class Pair{

private:

   T1 a;

   T2 b;

public:

   T1 &FIRST();

   T2 &SECOND();

   Pair(const T1 &A,const T2 &B):a(A),b(B){}

};

template<class T1,class T2>

T1 & Pair<T1,T2>::FIRST()

{

   return a;

}

 

template<class T1,class T2>

T2 & Pair<T1,T2>::SECOND()

{

   return b;

}

int main()

{

   Pair<string,int>r[2]={Pair<string,int>("zyh",3),Pair<string,int>("kjj",2)};

   r[0].FIRST()="jyh";

   r[0].SECOND()=6;

   cout<<r[0].FIRST()<<""<<r[0].SECOND()<<endl;

   return 0;

}

运行结果是“jyh 6”

当时很疑惑,为什么值改变了。后来写了个普通类测试一下:

#include<iostream>

using namespace std;

class a

{

   public:

   int num;

   int &haha();

   a(int n)

    {

       num=n;

    }

 

};

int & a::haha()

{

   return num;

}

int main()

{

   at1(3);

  t1.haha()=4;

   cout<<t1.num<<endl;

}

结果为4

说明普通类也是一样的。

然后又写了没有类的普通程序测试一下:

#include<iostream>

using namespace std;

int &haha(int a)

{

   return a;

}

int main()

{

  int a=3;

  haha(a)=4;

   cout<<a<<endl;

}

运行结果为3

值并没有改变。

 

然后我就想这事为什么呢?先开始不明白,后来想试试引用传递吧。就试了试:

#include<iostream>

usingnamespace std;

int&haha(int &a)

{

    return a;

}

intmain()

{

   int a=3;

   haha(a)=4;

    cout<<a<<endl;

}

 运行结果为4

值也改变了。

于是我明白了,其实是因为引用传递传递的是地址,如果值传递传递的只是副本而已。所以加了引用以后值就改变。

#include<iostream>

using namespace std;

class a

{

   public:

   int num;

   int haha();

   a(int n)

    {

       num=n;

    }

 

};

int a::haha()

{

   return num;

}

int main()

{

   at1(3);

  t1.haha()=4;

   cout<<t1.num<<endl;

}

提示出错了。


 

 

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值