我竟然不能在Strin类中重载friend operator+(……),请高手指点!

Benny1 2004-02-18 10:44:42


#include<iostream.h>
//using namespace std;

class String
{
public:
String(){str = NULL;length = 0;}
String(char *c);
~String();
String& operator =(String const& s);
String& operator ==(String const& s);
String &operator +=(const String& s);
// String& operator -(const String& s)throw();
char& operator [](int i)const throw();
inline int Length()const;
int FindKMP(const String& s)const;
friend String& operator +(const String& s,const String& s1);
friend ostream& operator << (ostream& out,String const &s);
private:
void Next();
int length;
char *str;
};

String::~String()
{
if(str != NULL){
// cout<<this->str<<endl;
delete [] str;
}
}

String&
String::operator =(const String& s)
{
if (str != NULL)
delete [] str;
str = new char[s.length+1];
if(str == NULL)
cout <<"error"<<endl;
for(int i=0;i<=s.length;i++)
this->str[i] = s.str[i] ;
this->length = s.length ;
return *this;
}

String::String(char *c)
{
int i = 0;
char *p = c;
while(*(p++))
i++;
length = i;
this->str = new char[length+1];
for(i=0;i<=length;i++)
this->str[i] = c[i];
}

String&
String::operator +=(const String& s)
{
String temp;
temp.length = this->length + s.length;
temp.str = new char[temp.length + 1];
for(int i=0;i<length;i++)
temp.str[i] = this->str[i];
for(;i<=temp.length ;i++)
temp.str[i] = s.str[i-length];
*this = temp;
return *this;
}

char& String::operator [](int i)const throw()
{
if(i<0||i>length)
throw i;
return this->str[i-1];
}

inline int String::Length ()const
{
return length;
}

ostream& operator << (ostream& out, const String& s)
{
if(s.str != NULL)
out << s.str ;
return out;
}

String& operator +(const String& s,const String& s1)

{
String temp = s;
temp += s1;
return temp;
}

void main()
{
String s = "sssss";
char *a = "aaaa";
String n ;
s[1] = 's';
// n = s + a;
n = a + s;
cout <<s[1]<<endl;
cout << a <<endl;
cout <<n <<endl;
}
...全文
39 26 打赏 收藏 转发到动态 举报
写回复
用AI写文章
26 条回复
切换为时间正序
请发表友善的回复…
发表回复

64,654

社区成员

发帖
与我相关
我的任务
社区描述
C++ 语言相关问题讨论,技术干货分享,前沿动态等
c++ 技术论坛(原bbs)
社区管理员
  • C++ 语言社区
  • encoderlee
  • paschen
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
  1. 请不要发布与C++技术无关的贴子
  2. 请不要发布与技术无关的招聘、广告的帖子
  3. 请尽可能的描述清楚你的问题,如果涉及到代码请尽可能的格式化一下

试试用AI创作助手写篇文章吧