質問

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?

役に立ちましたか?

解決

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.

他のヒント

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.

ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top