You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

C++中>>、<<运算符重载失效,程序运行异常求助

解决C++重载>>和<<运算符导致程序崩溃的问题

嘿,我瞅了下你的代码,问题其实挺明显的——你在重载输入运算符>>的时候犯了个关键错误,直接导致程序触发内存访问异常崩溃了。

错误原因拆解

你把输入运算符的第二个参数声明成了const Complex& a:

friend istream& operator>>(istream &is,const Complex&a);

对应的函数定义也是一样的:

istream& operator>>(istream&is,const Complex&a) {
    is>>a.re>>a.im;
    return is;
}

这里的const是致命问题!const修饰的引用意味着这个对象是只读的,你不能修改它的成员变量。但输入运算符的核心作用就是要把用户输入的值赋值给Complex对象的re和im,这就相当于试图往只读内存里写数据,直接触发了内存访问错误,也就是你看到的Process returned -1073741571 (0xC00000FD)报错。

另外还有个小细节:你的输出运算符里多了个多余的"a",会导致输出格式奇怪(比如输入3和4的话,会输出a3+j4),这应该不是你想要的效果,得去掉它。

修正后的完整代码

#include<iostream>
using namespace std;
class Complex {
private:
    double re;
    double im;
public:
    Complex(double x=0,double y=0):re(x),im(y){}
    friend ostream& operator<<(ostream&os,const Complex&a);
    // 去掉参数的const修饰符
    friend istream& operator>>(istream &is, Complex&a);
};
ostream& operator<<(ostream&os,const Complex&a) {
    // 去掉多余的"a",修复输出格式
    os << a.re << "+j" << a.im << endl;
    return os;
}
// 去掉参数的const修饰符
istream& operator>>(istream&is, Complex&a) {
    is >> a.re >> a.im;
    return is;
}
int main() {
    Complex d;
    cout << "enter the value of object: ";
    cin >> d;
    cout << "value is: " << d;
    return 0;
}

测试效果

现在运行程序,输入两个数字(比如3 4),程序会正常输出:

enter the value of object: 3 4
value is: 3+j4

完全不会再出现崩溃的情况了。

内容的提问来源于stack exchange,提问作者naman singh

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.07 09:52:52