求助:c++面试题
1. Are the following definitions valid? Why or why not?
const std::string hello = "Hello";
const std::string message = hello + ", world" + "!";
2.. Are the following definitions valid? Why or why not?
const std::string exclam = "!";
const std::string message = "Hello" + ", world" + exclam;
2是错误的
编译器报错:invalid operands of types `const char[6]' and `const char[8]' to b
inary `operator+'
谁能给个好的解释?
问题点数:40、回复次数:14Top
1 楼dengyejing(我不帅)回复于 2005-11-23 21:12:14 得分 10
因为"+"操作符的重载版本是:
string::operator+(char*)
所以,string类对象在前,char*在后是可以的,反过来就不行了!Top
2 楼oyljerry(【勇敢的心】→ ㊣提拉米苏√㊣)回复于 2005-11-23 21:39:04 得分 0
自己实现operatorTop
3 楼zl0126()回复于 2005-11-23 22:01:42 得分 0
markTop
4 楼ascmvi(ascmviascmviascmviascmviascmviascmviascmviascmvias)回复于 2005-11-23 23:08:48 得分 3
回复人: dengyejing(我不帅) ( ) 信誉:95
因为"+"操作符的重载版本是:
string::operator+(char*)
所以,string类对象在前,char*在后是可以的,反过来就不行了!
en ,应该是的Top
5 楼jang_168(jy)回复于 2005-11-24 13:51:58 得分 0
在vc里都是对的了!Top
6 楼hoya5121(饿了就喝水)回复于 2005-11-24 15:15:15 得分 0
回复人: jang_168(jy) ( ) 信誉:100 2005-11-24 13:51:00 得分: 0
在vc里都是对的了!
lz的意思是结果错误,而不是你说的编译正确
Top
7 楼jlu3389(激情的89)回复于 2005-11-24 15:25:37 得分 0
去看看运算符重载Top
8 楼yujing114(小靖)回复于 2005-11-24 16:04:43 得分 0
晕!!Top
9 楼mccxj(老鼠不逛街)回复于 2005-11-24 16:08:34 得分 4
const std::string exclam = "!";
const std::string message = "Hello" + /*", world" + */exclam;
换成这样就可以了..
为什么?因为好像c++里边不允许如此露骨的常量字符串连接....
........Top
10 楼suniuin(suniuin)回复于 2005-11-24 19:38:19 得分 10
2 错误的原因是无法计算 "Hello" + ", world", 因为加法是从左到右计算的, 而语言没有定义两个char *的加法, 所以报错。
1题没有问题因为第一个加法触发string string::operator +(const string&)返回以后可以继续加法操作!Top
11 楼sinon(菜农)回复于 2005-11-24 20:15:31 得分 10
suniuin(suniuin)正解
补充一下
1.中 hello + ", world" 后(hello + ", world")就变成是"string"类型了,所以(hello + ", world") + "!"....;就是"string"类型 用 string::operator +(const string&) 对(hello + ", world") 与"!" 进行字符串连结操作
2.中 "Hello" + ", world" 中间的"+"是标准运算符,所以处理不了两个char *的相加操作Top
12 楼caijize(砂子)回复于 2005-11-24 20:44:35 得分 3
回复人: suniuin(suniuin) ( ) 信誉:100 2005-11-24 19:38:20 得分: 0
2 错误的原因是无法计算 "Hello" + ", world", 因为加法是从左到右计算的, 而语言没有定义两个char *的加法, 所以报错。
1题没有问题因为第一个加法触发string string::operator +(const string&)返回以后可以继续加法操作!
Top
回复人: sinon(菜农) ( ) 信誉:100 2005-11-24 20:15:00 得分: 0
suniuin(suniuin)正解
补充一下
1.中 hello + ", world" 后(hello + ", world")就变成是"string"类型了,所以(hello + ", world") + "!"....;就是"string"类型 用 string::operator +(const string&) 对(hello + ", world") 与"!" 进行字符串连结操作
2.中 "Hello" + ", world" 中间的"+"是标准运算符,所以处理不了两个char *的相加操作
======================
高人!!看了提示后才想起来Top
13 楼yetcb(海山)回复于 2005-11-25 11:12:53 得分 0
结贴
多谢各位!!Top
14 楼luvybird()回复于 2005-11-28 22:45:35 得分 0
up
Top




