Borland C ++ Builder 6和字符串连接 [英] Borland C++ Builder 6 and string concatenation

查看:105
本文介绍了Borland C ++ Builder 6和字符串连接的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用Borland C ++ Builder 6尝试进行一些简单的字符串连接。但是,我遇到了我认为是一个有趣的问题。

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?

推荐答案

原因是 a 的类型为 char * (即:指向字符的指针),这意味着您在编写时

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.

创建 String 类型时, operator + 超载,因此

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

String a = "";
a + "b"

在<$ c $中添加了指向字符的指针c> String ,它具有自己的串联定义。

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

这篇关于Borland C ++ Builder 6和字符串连接的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆