c++中的字符串其中一种是从C语言中继承过来的,C语言中的字符串是char类型的数组,
定义
char a[20]="I am a boy“;
输出
cout<<a;
但是这种字符串不可以直接赋值,比如再定义一个字符数组 b[20],且给b赋值:b[20]=a[20];
这是编译器不会显示错误,但是输出会有错误,虽然这样,但是有时候我们要注意了
一
当结构体中有字符数组的时候
#include <iostream>
using namespace std;
struct birthday
{
int day;
int month;
int year;
};
struct student
{
int num;
char name[10];
birthday shengri;
};
int main()
{
student s1={01,"xiaozhong",{10,10,89}};
student s2;
cout<<s1.num<<' '<<s1.name<<' '<<s1.shengri.day<<' '<<s1.shengri.month
<<' ' <<s1.shengri.year<<endl;
s2=s1;
cout<<s2.num<<' '<<s2.name<<' '<<s2.shengri.day<<' '<<s2.shengri.month
<<' ' <<s2.shengri.year<<endl;
return 0;
}
这时候就是可以的
二
当类中的数据成员有字符数组的时候
// Note:Your choice is C++ IDE
#include <iostream>
#include <cstring>
using namespace std;
class String
{
private:
enum {SZ=80};
char str[SZ];
public:
String()
{str[0]='/0';}
String(char s[])
{strcpy(str,s);}
void display()
{cout<<str;}
void concat(String s2)
{if(strlen(str)+strlen(s2.str)<SZ)
strcat(str,s2.str);
else
cout<<"/nString too long ";
}
};
int main()
{
String s1("merry christmas!");
String s2="season's greetings!";
String s3;
cout<<"/ns1="; s1.display();
cout<<"/ns2="; s2.display();
cout<<"/ns3="; s3.display();
s3=s1;
cout<<"/ns3="; s3.display();
s3.concat(s2);
cout<<"/ns3="; s3.display();
cout<<endl;
return 0;
}
这时候也是可以的
所以字符串在应用的时候,我们应该加以区分。