string operator[]的奇怪现象,请大家指点,该如何解决
string operator[]的奇怪现象,请大家指点
#include <vector>
#include <string>
#include <algorithm>
#include <iterator>
#include <set>
//#incldue <iostream>
using namespace std;
// 标准 C++ 之前的 <iostream> 语法
#include <iostream.h>
ostream& operator < <(ostream &os,const string&);
int main()
{
string entry( "extravagant " );
string mycopy( "11111111111 ");
for ( int ix = 0; ix < entry.size(); ++ix )
{ mycopy[ ix ] = entry[ ix ]; }
entry[5]= 'a ';
cout < < mycopy;
cout < < entry;
int a = 1024;
int &ra = a;
int &rb = ra;
cout < < "ra= " < < ra < < " rb= " < < rb < <endl;
ra = 1025;
cout < < "ra= " < < ra < < " rb= " < < rb < <endl;
rb = 1026;
cout < < "ra= " < < ra < < " rb= " < < rb < <endl;
}
ostream& operator < <(ostream &os,const string& str)
{
os < < str.c_str() < <endl;
return os;
}
// 既然char & string::operator[](size_type pos)返回的引用,那么entry 和 mycopy 应该都会改变为extraaagant 而输出结果却只有entry变为extraaagant,对于INT & ra和rb的结果一致.
为何出现这样的情况?
------解决方案--------------------
我知道楼主的意思了,是不是说你觉得既然[]操作符的返回类型是引用,那么mycopy[ ix ] = entry[ ix ]之后,前者是后者的一个引用了呢?
要注意,[]的返回类型是引用,是对谁的引用?是对内部的char的引用,也就是说,mycopy[ ix ]
和entry[ ix ]分别是一个char类型的引用,就好像:char &a= 'x '; char &b= 'y ',其中a 和b分别
对应mycopy[ ix ]和entry[ ix ],那么这时候再mycopy[ ix ] = entry[ ix ],相当于a=b,很清
楚了吧,a并不是b的一个引用,而只是把b的值赋给了a.
这时候,a也等于y了,但再另b= 'z ',对a是没影响的,因为a和b本来就不相干
#include <vector>
#include <string>
#include <algorithm>
#include <iterator>
#include <set>
//#incldue <iostream>
using namespace std;
// 标准 C++ 之前的 <iostream> 语法
#include <iostream.h>
ostream& operator < <(ostream &os,const string&);
int main()
{
string entry( "extravagant " );
string mycopy( "11111111111 ");
for ( int ix = 0; ix < entry.size(); ++ix )
{ mycopy[ ix ] = entry[ ix ]; }
entry[5]= 'a ';
cout < < mycopy;
cout < < entry;
int a = 1024;
int &ra = a;
int &rb = ra;
cout < < "ra= " < < ra < < " rb= " < < rb < <endl;
ra = 1025;
cout < < "ra= " < < ra < < " rb= " < < rb < <endl;
rb = 1026;
cout < < "ra= " < < ra < < " rb= " < < rb < <endl;
}
ostream& operator < <(ostream &os,const string& str)
{
os < < str.c_str() < <endl;
return os;
}
// 既然char & string::operator[](size_type pos)返回的引用,那么entry 和 mycopy 应该都会改变为extraaagant 而输出结果却只有entry变为extraaagant,对于INT & ra和rb的结果一致.
为何出现这样的情况?
------解决方案--------------------
我知道楼主的意思了,是不是说你觉得既然[]操作符的返回类型是引用,那么mycopy[ ix ] = entry[ ix ]之后,前者是后者的一个引用了呢?
要注意,[]的返回类型是引用,是对谁的引用?是对内部的char的引用,也就是说,mycopy[ ix ]
和entry[ ix ]分别是一个char类型的引用,就好像:char &a= 'x '; char &b= 'y ',其中a 和b分别
对应mycopy[ ix ]和entry[ ix ],那么这时候再mycopy[ ix ] = entry[ ix ],相当于a=b,很清
楚了吧,a并不是b的一个引用,而只是把b的值赋给了a.
这时候,a也等于y了,但再另b= 'z ',对a是没影响的,因为a和b本来就不相干