![]() |
#2
yangfrancis2016-11-18 14:42
|
string s1="abc",s2="def";
string s3=s1+s2; 结果是“abcdef”
char s5=s2[1]; 结果是“e”*/
#include <iostream>
#include <string>
using namespace std;
class MyString
{
private:
int i;
char* string;
public:
MyString( ) //构造函数
{
string = new char [1];
string[0] = '\0';
i=1;
}
~MyString() //析构函数
{
delete [] string;
}
MyString(const MyString &rhs) //复制构造函数
{
i=strlen(rhs.string);
string = new char [i+1];
string[i] = '\0';
//strcpy(string,rhs.string);
}
MyString(const char* s) //用指针s所指向的字符串常量初始化atring类的对象
{
i=strlen(s);
string = new char [i+1];
string[i] = '\0';
//strcpy(string,s);
}
MyString operator+(const MyString &s) const //加法运算
{
int len = strlen(s.string);
char* str = new char [len+1];
str[len] = '\0';
strcat(string,s.string);
strcpy(str,string);
return MyString (str);
}
char operator[](int x) const //按下标查找元素
{
if (x>i||x<0)
{
cout<<"查找不在范围内!"<<endl;
}
else
return string[i];
}
friend ostream & operator<< (ostream &out, const MyString &s)
{
out<<s.string;
return out;
}
void show()
{
cout<<"加法运算结果为:"<<string[i]<<endl;
}
};
void main()
{
int m;
MyString s1 = "abc",s2="def",s3;
s3=s1+s2;
s3.show();
cout<<"请输入你要查找的信息的下标:";
cin>>m;
cout<<"查找的元素为:"<<s3[m]<<endl;
system("pause");
}

