C++中的友元函数和运算符重载
Friend Function and Operator Overloading in C++
我有以下代码,使用C++中的友元函数和运算符重载添加两个字符串Hi
和There
。
#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]=' ';
您也从未为新的较大字符串分配空间
相关文章:
- 使用C++中的模板和运算符重载执行矩阵运算
- 为什么这个运算符<重载函数对 STL 算法不可见?
- <T> 通过模板化运算符重载将 std::complex 乘以双倍
- C++20概念:需要运算符重载
- 使用赋值运算符重载从类中返回jobject
- 在运算符重载定义中使用成员函数(const错误)
- 字节到位运算符重载C++
- 为什么在运算符重载时需要参考?
- 类中 c++ 的运算符 + 重载
- 算术复合运算符重载为非成员
- 运算符重载 (+),用于添加两个具有 C++ 的数组
- 交换运算符 + 重载会导致无限递归
- 如何理解新的运算符重载?
- 向量保持复数的运算符重载
- 如何创建运算符重载?
- 链接列表运算符重载没有打印出我想要的内容
- C++:需要帮助了解运算符重载错误
- 使用模板化运算符重载 XOR 运算符失败
- 如何确保接受的C++模板类型使运算符重载?
- 运算符重载使用运算符+添加类模板