关于指针和数组,急
设计一个字符串类MyString,具有构造函数,析构函数,拷贝构造函数,重载运算符+,两个字符串相加,两个字符的长度比较,要求用指针和数组做,我之前用类做比较简单,但用指针和数组做怎样都想不出,哪位高手救救我
程序代码:#include <iostream.h>
#include <stdlib.h>
#include <string.h>
class MyString
{
char *s_sentence ;
public:
MyString(char s[]) //构造
{
s_sentence=s ;
}
MyString(MyString& p_s)//
{
s_sentence=p_s.s_sentence ;
}
char* operator +(MyString& o_s)//运算符+重载
{
char *sum=new char ;
int i=0,j=0;
while(*(s_sentence+i)!='\0')//先取第一个句子
{
*(sum+i)=*(s_sentence+i) ;
i++ ;
}
while(*(o_s.s_sentence+j)!='\0')//第二个
{
*(sum+i+j)=*(o_s.s_sentence+j) ;
j++ ;
}
*(sum+i+j)='\0' ; //去除程序运行后面多出的几个未知字符
return sum ;
}
static void compare(MyString& f,MyString& s)//长度比较
{
for(;;)
{
f.s_sentence++ ;
s.s_sentence++ ;
if(*s.s_sentence=='\0') {cout<<"The first sentence was longer\n" ;break ;} //比较一下哪个句子先结束
else if(*f.s_sentence=='\0'){cout<<"The second sentence was longer\n" ;break ;}
}
}
~MyString() //析构
{
cout<<"Delete the sentence" ;
}
} ;
int main()
{
MyString first("what's your name?"),second("i'm LiNing.") ;
char *p ;
p=first+second ;
cout<<"Add: "<<p<<"\n"<<"The result of compare: ";
MyString::compare(first,second) ;
system("pause") ;
}