1.*getName()返回值指向字符串的指针及构造函数
#include"cstring"
#include"iostream"
using namespace std;
class a
{
public:
a(char *c)
{
str=(char*)new char[strlen(c)+1];
strcpy(str,c);
}
char *getName()
{
return str;
}
private:
char *str;
};
int main()
{
a b("gjq");
cout<<b.getName()<<endl;
return 0;
}
2.字符串重载
#include<string.h>
#include<iostream>
using namespace std;
class strType
{
public:
strType(){*s='\0';}
strType(char *p) {strcpy(s,p);}//通过一个字符串指针来初始化字符数组
char *get() {return s;}
strType operator+(strType &s2);//重载+
strType operator=(strType &s2);//重载赋值操作符
int operator<(strType &s2);
int operator>(strType &s2);
int operator==(strType &s2);//重载一个逻辑运算符,也就是==操作符
private:
char s[100];
};
strType strType::operator+(strType &s2)
{
strType t;
strcpy(t.s,s);
strcat(t.s,s2.s);
return t;
}//这是个双目操作符,因此先建立一个StrType的临时变量t
strType strType::operator=(strType &s2)
{
strcpy(s,s2.s);
return *this;
}//this在这里就是指向等于号左边的那个StrType
int strType::operator<(strType &s2)
{
return strcmp(s,s2.s)<0;
}
int strType::operator>(strType &s2)
{
return strcmp(s,s2.s)>0;
}
int strType::operator==(strType &s2)
{
return strcmp(s,s2.s)==0;
}
void main()
{
strType str1("hello"),str2("world"),str3;
str3=str1+str2;
cout<<"str1="<<str1.get()<<endl;
cout<<"str2="<<str2.get()<<endl;
cout<<"str3=str1+str2="<<str3.get()<<endl;
str3=str1;
if(str1<str2)
cout<<"str1<str2"<<endl;
if(str1>str2)
cout<<"str1>str2"<<endl;
if(str1==str3)
cout<<"str1与str3相等"<<endl;
}