今天在《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;
}
提示出错了。