I'm having some trouble overloading my stream extraction operator in C++ for a hw assignment. I'm not really sure why I am getting these compile errors since I thought I was doing it right... Here is my code:
Complex.h
#ifndef COMPLEX_H
#define COMPLEX_H
class Complex
{
//friend ostream &operator<<(ostream &output, const Complex &complexObj) const;
public:
Complex(double = 0.0, double = 0.0); // constructor
Complex operator+(const Complex &) const; // addition
Complex operator-(const Complex &) const; // subtraction
void print() const; // output
private:
double real; // real part
double imaginary; // imaginary part
};
#endif
Complex.cpp
#include <iostream>
#include "Complex.h"
using namespace std;
// Constructor
Complex::Complex(double realPart, double imaginaryPart) : real(realPart), imaginary(imaginaryPart)
{
}
// addition operator
Complex Complex::operator+(const Complex &operand2) const
{
return Complex(real + operand2.real, imaginary + operand2.imaginary);
}
// subtraction operator
Complex Complex::operator-(const Complex &operand2) const
{
return Complex(real - operand2.real, imaginary - operand2.imaginary);
}
// Overload << operator
ostream &Complex::operator<<(ostream &output, const Complex &complexObj) const
{
cout << '(' << complexObj.real << ", " << complexObj.imaginary << ')';
return output; // returning output allows chaining
}
// display a Complex object in the form: (a, b)
void Complex::print() const
{
cout << '(' << real << ", " << imaginary << ')';
}
main.cpp
#include <iostream>
#include "Complex.h"
using namespace std;
int main()
{
Complex x;
Complex y(4.3, 8.2);
Complex z(3.3, 1.1);
cout << "x: ";
x.print();
cout << "\ny: ";
y.print();
cout << "\nz: ";
z.print();
x = y + z;
cout << "\n\nx = y + z: " << endl;
x.print();
cout << " = ";
y.print();
cout << " + ";
z.print();
x = y - z;
cout << "\n\nx = y - z: " << endl;
x.print();
cout << " = ";
y.print();
cout << " - ";
z.print();
cout << endl;
}
Compile erros:
complex.cpp(23) : error C2039: '<<' : is not a member of 'Complex'
complex.h(5) : see declaration of 'Complex'
complex.cpp(24) : error C2270: '<<' : modifiers not allowed on nonmember functions
complex.cpp(25) : error C2248: 'Complex::real' : cannot access private member declared in class 'Complex'
complex.h(13) : see declaration of 'Complex::real'
complex.h(5) : see declaration of 'Complex'
complex.cpp(25) : error C2248: 'Complex::imaginary' : cannot access private member declared in class 'Complex'
complex.h(14) : see declaration of 'Complex::imaginary'
complex.h(5) : see declaration of 'Complex'
Thanks!