C++中有多种创建string类型的方法,有继承C语言的部分,同时也有其独特的部分,现在我们就来分析一下各自的区别吧!
1)string类型直接创建对象
#include <iostream>
#include <string>
using namespace std;
int main(){
string s = "hello";
char &cs0 = s.at(0);
cs0 = 'N';
cout << s << endl;
s.append(" world");
cout << s << endl;
return 0;
}
运行结果:
这里可以看出string直接创建对象的话可以string对象中的值,因此可以判断后面的存在于栈或者堆中,但是s.append()可以使其动态扩展,因此,实际对象应该存在于堆中。网上给出的答案为:小于等于16bytes时候在栈中,大于16bytes在堆中。
2)char[]类型创建string对象
#include <iostream>
#include <string>
using namespace std;
int main(){
char s[6] = "hello";
s[0] = 'N';
cout << s << endl;
return 0;
}
运行结果:
运行结果显示,这种类型的string对象存在于栈中。
3)char*创建string对象
#include <iostream>
#include <string>
using namespace std;
int main(){
char*s = "hello";
s[0] = 'N';
cout << s << endl;
return 0;
}
运行结果:
我们发现,不能对这种类型的string对象进行修改,因此判断,这种对象存在于全局变量区的常量池中。
我们也可以换种程序代码证明这种内存分配情况:
1)char[]
#include <iostream>
#include <string>
using namespace std;
char* change(char* s){
s[0] = 'Q';
return s;
}
void change_chr(char s[]){
s[0] = 'Q';
cout << s << endl;
}
string change(string& s){
char &ch=s.at(0);
ch = 'Q';
return s;
}
int main(){
/*string s = "hello";
s = change(s);
cout << s << endl;
char* s1 = "hello";
s1 = change(s1);
cout << s1 << endl;*/
char s1[6] = "hello";
change_chr(s1);
cout << s1 << endl;
return 0;
}
运行结果:
2)char*
#include <iostream>
#include <string>
using namespace std;
char* change(char* s){
s[0] = 'Q';
return s;
}
void change_chr(char s[]){
s[0] = 'Q';
cout << s << endl;
}
string change(string& s){
char &ch=s.at(0);
ch = 'Q';
return s;
}
int main(){
char* s1 = "hello";
s1 = change(s1);
cout << s1 << endl;
/*string s = "hello";
s = change(s);
cout << s << endl;
char s1[6] = "hello";
change_chr(s1);
cout << s1 << endl;*/
return 0;
}
运行结果:
或者
#include <iostream>
#include <string>
using namespace std;
char* change(char* s){
s[0] = 'Q';
return s;
}
void change_chr(char s[]){
s[0] = 'Q';
cout << s << endl;
}
string change(string& s){
char &ch=s.at(0);
ch = 'Q';
return s;
}
int main(){
/*char* s1 = "hello";
s1 = change(s1);
cout << s1 << endl;
string s = "hello";
s = change(s);
cout << s << endl;
char s1[6] = "hello";
change_chr(s1);
cout << s1 << endl;*/
char* s1 = "hello";
change_chr(s1);
cout << s1;
return 0;
}
运行结果:
3)string
#include <iostream>
#include <string>
using namespace std;
char* change(char* s){
s[0] = 'Q';
return s;
}
void change_chr(char s[]){
s[0] = 'Q';
cout << s << endl;
}
string change(string& s){
char &ch=s.at(0);
ch = 'Q';
return s;
}
int main(){
/*char* s1 = "hello";
s1 = change(s1);
cout << s1 << endl;
string s = "hello";
s = change(s);
cout << s << endl;
char s1[6] = "hello";
change_chr(s1);
cout << s1 << endl;
char* s1 = "hello";
change_chr(s1);
cout << s1;*/
string s = "hello";
s = change(s);
cout << s << endl;
return 0;
}
运行结果: