2008年3月21日 星期五

CSE2305 Topic 19: C++ Operator Overloading

CSE2305 Topic 19: C++ Operator Overloading:

An important use of operator overloading¤

  • Because we can overload the operators << and >>, we can allow user-defined classes¤ to perform I/O just like inbuilt types (!)
  • For example:
    #include 

    class Complex
    {
    public:
    Complex(float re, float im)
    : myReal(re), myImag(im)
    {}

    friend istream& operator>>(istream&, Complex&);
    friend ostream& operator<<(ostream&, const Complex&);

    private:
    float myReal;
    float myImag;
    };

    istream& operator>>(istream& in, Complex& c)
    {
    double real, imag;
    in >> real >> imag;
    if (in.good())
    {
    c.myReal = real;
    c.myImag = imag;
    }
    return in;
    }

    ostream& operator<<(ostream& out, const Complex& c)
    {
    out << "(" << c.myReal << "," << c.myImag << ")";
    return out;
    }

沒有留言: