复杂数c ++程序中的分段错误

时间:2018-01-22 23:59:33

标签: c++ segmentation-fault fault

我正在使用c ++编写一个程序来重载运算符以处理复数。程序运行时,我得到输出:

  

注意:请输入+ bi格式的复数

     

分段错误

我一直在查看我的代码一段时间,并且不能为我的生活找到我犯错的地方。该程序编译没有错误。如果你能帮我找到我错的地方,请告诉我。这是我的代码:

#include <iostream>
#include <cmath>

using namespace std;

class Complex
{
public:

//constructors
    Complex();
    Complex(double r1);
    Complex(double r1, double r2);

//mutators
    void setReal(double newNum);
    void setComp(double newNum);

//accessor functions
    double getReal() const;
    double getComp() const;

//Friend functions
//overloading bindary operators
friend const Complex operator + (const Complex& x, const Complex& y);
friend const Complex operator - (const Complex& x, const Complex& y);
friend const Complex operator * (const Complex& x, const Complex& y);

//overloaded boolean
friend bool operator == (const Complex& x, const Complex& y);

//overloading << for output and >> for input 
friend ostream& operator << (ostream& outputStream, const Complex& comp);
friend istream& operator >> (istream& inputStream, const Complex& comp);

private:
//private member variables
double a; //a is the real part, while b is the complex part
double b;


};

int main()
{ char ans;
Complex comp1, comp2;
    cout<<"Note: please enter complex numbers in a+bi format "<<endl;
cout << "Complex number 1: ";
cin >> comp1;
cout << "Complex number 2: ";
cin >> comp2;
cout << endl << "The sum is: " << comp1 + comp2;
return(0);
}

Complex::Complex()
{
a = 0;
b = 0;
}

Complex::Complex(double r1)
{
a = r1;
b = 0;
}

Complex::Complex(double r1, double r2)
{
a = r1;
b = r2;
}

void Complex::setReal(double newNum)
{
a = newNum;
}

void Complex::setComp(double newNum)
{
b = newNum;
}

double Complex::getReal() const
{
return a;
}

double Complex::getComp() const
{
return b;
}

const Complex operator + (const Complex& x, const Complex& y)
{
int real, comp;
real = x.a + y.a;
comp = x.b + y.b;
Complex compSum(real, comp);
return compSum;
 }

const Complex operator - (const Complex& x, const Complex& y)
{
int real, comp; 
real = x.a - y.a;
comp = x.b - y.b;
Complex compDiff(real, comp);
return compDiff;
}

const Complex operator * (const Complex& x, const Complex& y)
{
int real, comp;
real = (x.a * y.a) - (x.b * y.b);
comp = (x.a * y.b) + (x.b * y.a);
Complex compProd(real, comp);
return compProd;
}

bool operator == (const Complex& x, const Complex& y)
{
return ((x.a == y.a)&&(x.b == y.b));
}

ostream& operator << (ostream& outputStream, const Complex& comp)
{
outputStream << comp.a << "+"<<comp.b<<"i";
return outputStream;
}

istream& operator >> (istream& inputStream, const Complex& comp)
{
char plus, iLet;
inputStream >> comp.a >> plus >> comp.b >> iLet;
return inputStream;
 }

1 个答案:

答案 0 :(得分:0)

在更改值时,只需从const运算符中的Complex&参数中删除>>

friend istream& operator >> (istream& inputStream, Complex& comp);