Native/C++

간단하게 짠 연산자 소스 (operator)

aucd29 2013. 10. 2. 18:58
[code]
#include <Turboc.h>
#include <IOSTREAM>

using namespace std;

struct appendData
{
    char name[20];
    int age;
};

class operatorTest
{
    // cout관련
    friend ostream &operator <<(ostream &c, const operatorTest &target);
    friend ostream &operator <<(ostream &c, const operatorTest *target);

    // 연산자 관련
    friend const operatorTest operator +(const operatorTest &source1, const operatorTest &source2);
    friend const operatorTest operator +(const operatorTest &source1, const operatorTest *source2);
    friend const operatorTest operator +(const operatorTest *source1, const operatorTest &source2);

private:
    int i;
    int j;
    appendData info;
    
public:
    operatorTest(int ai, int aj, char *name, int age): i(ai), j(aj)
    {
        strcpy(info.name, name);
        info.age = age;
    }
    operatorTest(){};
    
    // 증감 관련
    operatorTest &operator ++()
    {
        i++;
        j++;

        return *this;
    }
    operatorTest &operator ++(int)
    {
        return ++*this;
    }

    bool operator ==(const operatorTest &target) const
    {
        return (i==target.i && j==target.j);
    }

    bool operator !=(const operatorTest &target) const
    {
        return !(*this == target);
    }
    
    // 배열 연산자 관련
    int &operator [](int what)
    {
        if(what == 0)
            return i;
        else
            return j;
    }

    // 참조연산자 관련
    //appendData *operator->() { return &info; }
};

ostream &operator <<(ostream &c, const operatorTest &target)
{
    c << "i:" << target.i << ", j:" << target.j << ", name:" << target.info.name << ", age: " << target.info.age;
    return c;
}

ostream &operator <<(ostream &c, const operatorTest *target)
{
    c << "i:" << target->i << ", j:" << target->j << ", name:" << target->info.name << ", age: " << target->info.age;
    return c;
}

const operatorTest operator +(const operatorTest &source1, const operatorTest &source2)
{
    operatorTest dumy;

    dumy.i = source1.i + source2.i;
    dumy.j = source1.j + source2.j;
    dumy.info.age = source1.info.age;
    strcpy(dumy.info.name, source1.info.name);

    return dumy;
}

const operatorTest operator +(const operatorTest &source1, const operatorTest *source2)
{
    return (source1+*source2);
}

const operatorTest operator +(const operatorTest *source1, const operatorTest &source2)
{
    return (*source1+source2);
}



void main()
{
    operatorTest a(50, 20, "kimJinHee", 30);
    operatorTest b(100, 2, "AhnYoungEun", 24);
    operatorTest *c;
    c = new operatorTest(300, 200, "choicheoldong", 27);
    operatorTest d;
    
    cout << b << endl;
    cout << c << endl;

    d = a+c;
    cout << d << endl;

    ++a;
    cout << a << endl;
    a++;
    cout << a << endl;

    if(a == b)
        cout << "same" << endl;
    else
        cout << "different" << endl;

    cout << a[0] << endl;

}[/code]