niedziela, 29 grudnia 2013

C++ overloading operators part 1 /przeładowanie operatorów cześć 1

This is simple, when You see it;
________________________________
#include <iostream>
using namespace std;
class A
{
public:
    A(int X=0,int Y=0):x(X),y(Y){}    //construktor conversions
    void write();
    A operator +(const A &o1);
    A operator ++ (int);
    A operator ++ ();
    A operator +=(const A &o1);
    A operator =(const A &o1);
   int operator ==(const A &o1);
private:
    int x,y;

};
void A::write()
{
    cout<<"x="<<x<<" y="<<y<<endl;
}

A A::operator +(const A &o1)    //           1
{
    A result;
    result.x=x+o1.x;
    result.y=y+o1.y;
    return result;
}
A A::operator ++(int)          //          2
{
    x++;
    y++;
    return *this;

}
A A::operator ++()              //          3
{
    ++x;
    ++y;
    return *this;
}
A A::operator +=(const A &o1)  //  4
{
    x+=o1.x;
    y+=o1.y;
     return *this;
}
A A::operator =(const A &o1)   // 5
{
    x=o1.x;
    y=o1.y;
    return *this;
}
int A::operator==(const A &o1)    //6
{
    if(x!=o1.x) return 0;
    else if(y!=o1.y) return 0;
    else return 1;
}
int main()
{
    A o1(1,2),o2(10,20);
    A o3=o1+o2;
    cout << " (1) o3=o2+o1" << endl;
    o3.write();
    cout << " (2) o1++" << endl;
    o1++;
    o1.write();
    cout << " (3) ++o1" << endl;
    ++o1;
    o1.write();
    cout << " (4) o1+=o2" << endl;
    o1+=o2;
    o1.write();
     cout << " (5) o5=o1" << endl;
    A o5=o1;
    o5.write();
     cout << " (6) test ==" << endl;
     if(o5==o1) cout << " SUCCES" << endl;
     if(o5==o2) {}
     else cout << " SUCCES" << endl;
    return 0;
}

Brak komentarzy:

Prześlij komentarz