实验四 多态性
一、实验目的
1、理解运算符重载函数与运算符重载的方法;
2、掌握运算符重载为成员函数及重载为友元函数的方法;
3、掌握虚函数的定义与使用方法;
4、掌握纯虚函数与抽象类的定义与使用方法。
二、实验内容及步骤
仿照标准字符串类string ,设计一个自己的字符串类String。
主要完成以下任务:
1)数据成员是字符指针,可自动适应不同的串长度。
2)串复制,既可使用字符串常量进行复制,也可以使用其他的字符串对象进行复制。
3)串赋值。既可赋值为字符串常量,也可以赋值为使用其他的字符串对象。
4)串连接。重载“+”和“+=”。
5)重载下标运算符[]。
6)串比较。重载 “”和“<”。
7)字符串输入和输出。重载“>>”和“<<”。
编程完成各函数的定义,并进行如下测试。
int main()
{
String s1(“Help!”),s2(“Good!”),s3(s2),s4,s5;
cout<<“s1=”<<s1<<endl;
s3=“Hello!”;
cout<<“s3=”<<s3<<endl;
s3=s2;
cout<<“s3=”<<s3<<endl;
s3+=s2;
cout<<“s3=”<<s3<<endl;
cin>>s4;
cout<<“s4=”<<s4<<endl;
s5=s3+s4;
cout<<“s5=”<<s5<<endl;
s5[0]=‘g’;
cout<<“s5=”<<s5<<endl;
cout<<“strlen(s5)=”<<s5.Length()<<endl;
cout<<boolalpha<<(s3==s1)<<endl;
cout<<boolalpha<<(s3<s1)<<endl;
}
#include<iostream>
#include<cstring>
using namespace std;
class String
{
private:
char *list;
public:
String();
String(char *l);
String(const String &s);
~String();
char* GetList();
String &operator=(String &s);//复制
String &operator=(char *l);//赋值
String &operator+(String &s);//连接
String &operator+=(String &s);//连接
char &operator[](int);
bool operator==(String &s);
bool operator<(String &s);
int Length();
};
String::String()
{ list=new char[5];strcpy(list,"NULL"); }
String::String(char *l)//申请空间时需多申请一个
{ list=new char[strlen(l)+1]; strcpy(list,l); }
String::String(const String &s)
{ list=new char[strlen(s.list)+1];strcpy(list,s.list); }
String::~String()
{
delete []list;
}
char* String::GetList()
{
return list;
}
String &String::operator=(String &s) //复制
{
delete []list;
list=new char[strlen(s.list)+1];
strcpy(list,s.list);
return *this;
}
String &String::operator=(char *l) //赋值
{
delete []list;
list=new char[strlen(l)+1];
strcpy(list,l);
return *this;
}
String &String::operator+(String &s) //连接
{
strcat(list,s.list);
return *this;
}
String &String::operator+=(String &s) //连接
{
strcat(list,s.list);
return *this;
}
char &String::operator[](int i)
{
return list[i];
}
bool String::operator==(String &s)
{
if(strcmp(list,s.list)==0)
return true;
return false;
}
bool String::operator<(String &s)
{
if(strcmp(list,s.list)<0)
return true;
return false;
}
int String::Length()
{
return strlen(list);
}
ostream & operator<<(ostream &out,String &s)
{
out<<s.GetList();
return out;
}
istream & operator>>(istream &in,String &s)
{
in>>s.GetList();
return in;
}
int main()// 主函数
{
String s1("Help!"),s2("Good!"),s3(s2),s4,s5;
cout<<"s1="<<s1<<endl;
s3="Hello!";
cout<<"s3="<<s3<<endl;
s3=s2;
cout<<"s3="<<s3<<endl;
s3+=s2;
cout<<"s3="<<s3<<endl;
cin>>s4;
cout<<"s4="<<s4<<endl;
s5=s3+s4;
cout<<"s5="<<s5<<endl;
s5[0]='g';
cout<<"s5="<<s5<<endl;
cout<<"strlen(s5)="<<s5.Length()<<endl;
cout<<boolalpha<<(s3==s1)<<endl;
cout<<boolalpha<<(s3<s1)<<endl;
return 0;
}
下面是结果:
s1=Help!
s3=Hello!
s3=Good!
s3=Good!Good!
very
s4=very
s5=Good!Good!very
s5=good!Good!very
strlen(s5)=14
false
true
Process returned 0 (0x0) execution time : 5.884 s
Press any key to continue.