-
overloading <<
I'm trying to figure out how to overload << so I can print a complex number just by
cout << c_num;
I'm getting a compilation error saying
k:\cfiles\cis285\complex\complex.h(24) : error C2270: '<<' : modifiers not allowed on nonmember functions
How can I correct this?
(The error message references the line that begins:
"friend ostream& operator<<..."
Code:
#ifndef _complex_h
#define _complex_h
#include <iostream>
using namespace std;
class Complex{
public:
Complex(double re = 0, double im = 0){_real = re, _imag = im;}
Complex operator+( const Complex& num2) const {
Complex result(_real + num2._real, _imag + num2._imag);
return result;}
Complex operator-( const Complex& num2) const {
Complex result(_real - num2._real, _imag - num2._imag);
return result;}
friend ostream& operator<<( ostream& os, const Complex& cnum) const {
return os << cnum._real << " + " << cnum._imag << "i";}
// void print() {
// cout << _real << " + " << _imag << "i";}
private:
double _real, _imag;
};
#endif
-
There is a built in STL container for complex numbers, the << operator is already taken care of:
Code:
#include <complex>
#include <iostream>
using namespace std;
int main()
{
complex<double> c1(3.2,6.1);
cout << "Complex value c1: " << c1 << endl;
return 0;
}
Should output something along the lines of:
Complex value c1: (3.2,6.1)
-
Code:
class Complex{
public:
Complex(double re = 0, double im = 0){_real = re, _imag = im;}
Complex operator+( const Complex& num2) const {
Complex result(_real + num2._real, _imag + num2._imag);
return result;}
Complex operator-( const Complex& num2) const {
Complex result(_real - num2._real, _imag - num2._imag);
return result;}
//friend ostream& operator<<( ostream& os, const Complex& cnum) const {
// return os << cnum._real << " + " << cnum._imag << "i";}
friend ostream& operator<<(ostream& os,const Complex& cnum){
return os << cnum._real << " + " << cnum._imag << "i";
}
// void print() {
// cout << _real << " + " << _imag << "i";}
private:
double _real, _imag;
};
-
Remove the "const" as The Dog pointed out.
"Go Dawgs!"
gg (UGA grad)
-