自定义String类,重载下列运算符:
下标运算符[ ]、赋值运算符=、连接运算符+ 、输出运算符<<、输入运算符>>,能对两个字符串进行相应操作,在主函数中测试之。
函数接口定义:
char& String::operator[](int i);
String& String::operator=(const String& a) ;
String operator+(const String& a,const String& b);
ostream& operator<<(ostream& out,const String& a);
istream& operator>>(istream& in,String& a);
char& operator[](int i) 实现返回String对象下标为i的字符;
String& operator=(const String& a) 实现对象间的赋值操作,注意防范String对象对自身的赋值;
String operator+(const String& a,const String& b) 实现两个String对象的连接操作,并返回结果;
ostream& operator<<(ostream& out,const String& a) 实现对String对象的输出操作;
istream& operator>>(istream& in,String& a) 实现对String对象的输入操作,字符串长度不超过1000,可包含空格。
裁判测试程序样例:
#include<iostream>
#include<cstring>
using namespace std;
class String {
private:
char *s;
int len;
public:
String(char*t = NULL) {
if(t == NULL) {
s = new char('\0');
len = 1;
} else {
s = new char[len = strlen(t) + 1];
strcpy(s,t);
}
}
~String() {delete []s;}
char& operator[](int i);
String& operator=(const String& a) ;
friend String operator+(const String& a,const String& b);
friend ostream& operator<<(ostream& out,const String& a);
friend istream& operator>>(istream& in,String& a);
};
int main() {
String a,b,c;
int x;
while(cin >> a >> b >> x) {
getchar();
c=a;
cout << "testing =: " << c<<endl;
c=a+b;
cout << "testing +: " << c<<endl;
cout << "testing []: " << c[x]<<endl;
}
return 0;
}
/* 请在这里填写答案 */
输入样例:
在这里给出一组输入。例如:
I love C++ programming.
me too.
4
输出样例:
在这里给出相应的输出。例如:
testing =: I love C++ programming.
testing +: I love C++ programming.me too.
testing []: v