C ++复数运算符重载

时间:2014-07-18 22:21:28

标签: c++ operator-overloading operator-keyword

我正在尝试重载>>和<<用于复数类的运算符。出于某种原因,我的<<和>>函数无法访问复杂对象的实部和虚部,即使我已经让他们成为了班级的朋友。

Complex.h:

#ifndef COMPLEX_H
#define COMPLEX_H

class Complex
{

friend std::ostream &operator<<(std::ostream &out, const Complex &c);
friend std::istream &operator>>(std::istream &, Complex &);

public:
     explicit Complex(double = 0.0, double = 0.0); // constructor
     Complex operator+(const Complex &) const;
     Complex operator-(const Complex &) const;

#endif

Complex.cpp:

#include "stdafx.h"
#include "Complex.h"
#include <iostream>
using namespace std;

istream &operator>>(istream &input, Complex &complex) // input
{
     cout << "enter real part:\n";
     input >> complex.real;
     cout << "enter imag part: \n";
     input >> complex.imaginary;
     return input;
}

std::ostream &operator<<(std::ostream &out, Complex c)     //output
{
     out<<"real part: "<<c.real<<"\n";
     out<<"imag part: "<<c.imag<<"\n";
     return out;
}

1 个答案:

答案 0 :(得分:2)

没有与您定义的相同功能的朋友。你结识了第一个,并定义了第二个:

friend std::ostream &operator<<(std::ostream &out, const Complex &c);
       std::ostream &operator<<(std::ostream &out,       Complex  c)

此外,成员名为imaginary还是imag

 input >> complex.imaginary;
 out<<"imag part: "<<c.imag<<"\n";