【笔记】关于字符串相加

原文地址:http://www.cnblogs.com/volcanol/p/4001057.html   非常感谢原作者

Exp:  关于字符串的相加  str1 + str2

复制代码
[root@localhost cpp_src]# cat test.cpp 
#include <iostream>
#include <string>

using std::cin;
using std::cout;
using std::endl;
using std::string;

int main()
{
    string str1;
    string str2("hi,");

    str1="volanol";
    
    string str3= str2+ str1;
    cout<<str3<<endl;

    return 0;
}
复制代码

执行结果如下所示:

[root@localhost cpp_src]# g++ test.cpp 
[root@localhost cpp_src]# ./a.out 
hi,volanol

    这段代码,演示了  string类型的 str1 + str2 的效果,同时演示了  string str("volcanol"); 这样的直接初始化

方式。

  string对象的 + 操作可以与字符串字面值进行操作,如下:

Exp:

复制代码
[root@localhost cpp_src]# cat test.cpp 
#include <iostream>
#include <string>

using std::cin;
using std::cout;
using std::endl;
using std::string;

int main()
{
    string str1;
    string str2("hi,");

    str1="volanol";
    
    string str3= str2+ str1;
    cout<<str3<<endl;

    string str4= str3 + "nice to meet you"; //字符串字面值 + 运算
    cout<<str4<<endl;

    return 0;
}
复制代码

执行结果如下:

[root@localhost cpp_src]# g++ test.cpp 
[root@localhost cpp_src]# ./a.out 
hi,volanol
hi,volanolnice to meet you

  同时需要注意的是:  + 操作符使用的时候,其左、右操作必须有一个是 string对象,不能都是引号形式的,否则是错误的。

例如:

复制代码
 1 #include <iostream>
 2 #include <string>
 3 
 4 using std::cin;
 5 using std::cout;
 6 using std::endl;
 7 using std::string;
 8 
 9 int main()
10 {
11     string str1;
12     string str2("hi,");
13 
14     str1="volanol";
15     
16     str1 = "hi," + str1;
17 
18     str2= "hi,"+"volcanol";
19 
20     cout<<str1<<endl;
21     cout<<str2<<endl;
22 
23     return 0;
24 }
复制代码

编译的情况如下所示:

[root@localhost cpp_src]# g++ test.cpp 
test.cpp: In function ‘int main()’:
test.cpp:18: 错误:操作数类型 ‘const char [4]’ 和 ‘const char [9]’ 对双目 ‘operator+’ 而言无效
[root@localhost cpp_src]# 

  可以发现 18 行出现错误了, 说 const char[4] 和 const char [9] 不能用双目运算符进行计算, 

原因上面的提示信息已经说的很明白了,const char类型不支持+ 操作。

A mind needs books like a sword needs a whetstone.
原文地址:https://www.cnblogs.com/yzsatcnblogs/p/4335234.html