在重载复杂类的运算符>>时发生分段错误

occurs segmentation fault while overloading operator >> for the Complex class

本文关键字:gt 分段 错误 重载 运算符 复杂      更新时间:2023-10-16

如果我想在我的 c++ 程序中使用这样的句子,

while (cin >> c)
{
cout << c << endl;
}

c 是我之前定义的一个复杂类。

如何重载复杂类的运算符>> 我尝试了两种方法,但是当程序第二次运行上述句子cin>>c时,由于分割错误,它们都失败了,
and the first method is 
friend istream& operator >> (istream& in, Complex& right)
{
char a;
char temp[50];
int cnt = 0;
double i = 0;
double r = 0;
while (in >> a)
{
if (a == ')')
{
temp[cnt] = a;
break;
}
temp[cnt++] = a;
}
sscanf(temp, "(%lf,%lf)", &r, &i);
right.real = r;
right.imag = i;
}

第二种方法是

friend istream& operator >> (istream& in, Complex& right)
{
double r = 0;
double i = 0;
in.ignore();
in >> r;
in.ignore();
in >> i;
in.ignore();
right.real = r;
right.imag = i;
}

我的输入是这样的 (1.5,2)(1,2.5)(1.5,2.5)(0,0)(1,2)

谁能给出一些提示?

在 temp 末尾添加 nullptr 后,

我仍然遇到同样的问题,以下是错误

程序接收信号SIGSEGV,分段错误。 主.cpp:75 的 f () 中的0x0000000000401285 75 同时 (CIN>> c) (GDB) S

问题很可能是您使用不以 null 结尾的字符串调用sscanf

while (in >> a)
{
if (a == ')')
{
temp[cnt] = a;
break;
}
temp[cnt++] = a;
}
// Need to null terminate temp
temp[cnt+1] = '';
sscanf(temp, "(%lf,%lf)", &r, &i);

首先,它是operator>>而不是operator >>(注意缺少空格)。

其次,为什么不只是这个:

friend istream& operator>> (istream& in, Complex& right)
{
in >> right.real;
in >> right.imag;
}

注意:您还必须重载operator<<才能cout << c << endl工作。