Borland C++ Builder 6 and string concatenation

半世苍凉 提交于 2019-12-10 10:31:30

问题


I'm using Borland C++ Builder 6 to try to do some simple string concatenation. However, I have run into what I think is an interesting issue.

Everything I am able to find online states that I should be able to do something as simple as this:

String word = "a" + "b" + "c";

However, when I try to compile this code, I get an "Invalid pointer addition" error. I could go as far as assigning each part to its own variable and adding each of those together to get the desired output. However, I think that's unnecessary given how simple of an example this is.

The only way I have been able to get something similar to the above to work as desired is by doing this:

String a = "";
String word = a + "a" + "b" + "c";

My question is this: why would the second example work just fine but not the first one?


回答1:


The reason is that the type of "a" is char* (i.e.: pointer-to-char), which means when you write

"a" + "b"

you are trying to add to pointers together, which is not allowed.

When you create a String type, the operator+ is overloaded so

String a = "";
a + "b"

adds a pointer-to-char to a String, which has its own defintion of concatenation.




回答2:


I'm not quite sure, but this is probably because of arguments. "a" in the first line is char*, so adding other strings still makes the result of char* and it is not possible to directly assign it o a String object. The second case shows, that if the first argument is of String type, all results are also Strings, so assignment is possible.



来源:https://stackoverflow.com/questions/10917797/borland-c-builder-6-and-string-concatenation

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!