C++中让人吃惊的做法,给返回值赋值!
我们看一段程序:
,输出结果是Hello!;因为返回值是个全局引用,所以是合法的,注意,一定不要返回局部引用,那样说不定会出现什么,它会在运行时打击你!呵呵,如果我们不想给返回值赋值.只需加上const即可!
#include
<
iostream
>
#include < string >
#include < cstdlib >
using namespace std;
char & get_val( string & str, string ::size_type ix) ... {
return str[ix];
}
int main() ... {
string str = “hello!”;
get_val(str, 0) = ‘H’;
cout << str << endl;
return EXIT_SUCCESS;
}
#include < string >
#include < cstdlib >
using namespace std;
char & get_val( string & str, string ::size_type ix) ... {
return str[ix];
}
int main() ... {
string str = “hello!”;
get_val(str, 0) = ‘H’;
cout << str << endl;
return EXIT_SUCCESS;
}
很多人可能吓坏了
如下:
, 即会在编译时出错 : error C2166: l-value specifies const object;
#include
<
iostream
>
#include < string >
#include < cstdlib >
using namespace std;
const char & get_val( string & str, string ::size_type ix) ... { //改动在这里,在开头加上const;
return str[ix];
}
int main() ... {
string str = “hello!”;
get_val(str, 0) = ‘H’;
cout << str << endl;
return EXIT_SUCCESS;
}
#include < string >
#include < cstdlib >
using namespace std;
const char & get_val( string & str, string ::size_type ix) ... { //改动在这里,在开头加上const;
return str[ix];
}
int main() ... {
string str = “hello!”;
get_val(str, 0) = ‘H’;
cout << str << endl;
return EXIT_SUCCESS;
}
如此