samedi 26 novembre 2016

How exactly can I overload the ">>" operator for my own class?

I have the following header file for my class:

#ifndef DEF_COMPLEXE
#define DEF_COMPLEXE

#include <iostream>

class Complexe
{
    public:

    double getReel() const;
    double getImag() const;
    void setReel(double reel);
    void setImag(double imag);

    friend std::istream& operator>>(std::istream& input, Complexe& c);
    //friend std::istream& operator>>(std::istream&); 

    private:

    double m_reel;
    double m_imag;
};

std::istream& operator>>(std::istream &input, Complexe& c);

#endif

Below is the .cpp file of my class:

#include "Complexe.h"

using namespace std;

/* Getters and setters ... */

istream& Complexe::operator>>(istream& input, Complexe& c)
{
    input >> c.m_reel;
    input >> c.m_imag;
    return input;
}

/**
istream& Complexe::operator>>(istream& input)
{
    input >> m_reel;
    input >> m_imag;
    return input;
}
*/

I want to overload the >> operator to be able input data to change (or initialize) the values of some member variables in my class.

As you can see, I have tried two kinds of overloading fucntions to overload the operator>>,

but, when I use the first function friend std::istream& operator>>(std::istream& input, Complexe& c); , the compiler gave me: ‘std::istream& Complexe::operator>>(std::istream&, Complexe&)’ must take exactly one argument


And When I use the second fucntion friend std::istream& operator>>(std::istream&); , the compiler gave me : ‘std::istream& operator>>(std::istream&)’ must take exactly two arguments

my test code in the main.cpp is like this :

Complexe c;
cin >> c;


So what is wrong with my code? What should I do to make inputting data into my member variables of my class possible?

Aucun commentaire:

Enregistrer un commentaire