C++中的友元函数和运算符重载

Friend Function and Operator Overloading in C++

本文关键字:运算符 重载 函数 友元 C++      更新时间:2023-10-16

我有以下代码,使用C++中的友元函数和运算符重载添加两个字符串HiThere

   #include<iostream.h>
#include<conio.h>
class STRING
{
 char *str;
 public:
     STRING(char *p) { str=p; }
     STRING(STRING& s) { str=s.str; }
     friend STRING operator+(STRING &s1,STRING& s2);
     friend ostream& operator<<(ostream& dout,STRING& s)
     {
      dout<<s.str;
      return dout;
     }
};
STRING operator+(STRING &s1,STRING& s2)
{
 STRING x(s1); int i,j=0;
 for(i=0;x.str[i]!='';i++);
 x.str[i]=' ';
 while((x.str[++i]=s2.str[j++])!='');
 x.str[i]='';
 return x;
}
void main()
{
 clrscr();
 cout<<"nntt";
 STRING s1="Hi";     cout<<" String s1: "<<s1<<"nntt";
 STRING s2="There"; cout<<" String s2: "<<s2<<"nntt";
 STRING s3=s1+s2;     cout<<" S1+S2 is : "<<s3<<"nntt";
 getch();
}

当我构建解决方案时,它没有显示任何错误,但当我运行这个程序时,我在弹出框中得到以下错误

Unhandled exception at 0x011f1506 in Program 6.exe: 0xC0000005: Access violation writing location 0x011f7860.

您正在传递字符串文字,然后修改它们-这是不允许的,您不能修改"Hi"或"There"

x.str[i]=' ';

您也从未为新的较大字符串分配空间