본문 바로가기

Code/C++

[C++] class 생성/ friend / spy

 

#include <iostream>

using namespace std;

class Point {

private:

        int x;

        int y;

        static int cntObj;

//      int* list;

//      ofstream fout;

public:

        Point():x(0),y(0){

//             list = new int[100];

//             fout.open("file.txt");

               cntObj++;

        } //default

        Point(int _x,int _y) : x(_x),y(_y) {

               cntObj++;

        }

        ~Point(){

               cout << "Destructed.." << endl;

//             delete[] list;

//             fout.close();

        }   // 소멸자

        void setXY(int _x, int _y) {

               this->x = _x;

               this->y = _y;

        }

        int getX() const { return x; }

        int getY() const { return y; }

        static int getCntObj() { return cntObj; }

        friend ostream& operator<<(ostream& cout, const Point& pt);

        friend Point operator+(const Point& pt1, const Point& pt2);

        friend class SpyPoint;

};

//static member변수는 반드시 외부에서 초기화해줘야한다

int Point::cntObj = 0;

class SpyPoint {

public:

        void hacking(const Point& pt) {

               cout << "x: " << pt.x << endl;

               cout << "y: " << pt.y << endl;

               cout << "CntObj: " << pt.cntObj << endl << endl;

        }

};

// cout << pt -> <<(cout, pt)

// int &x = func(y);

ostream& operator<<(ostream& cout, const Point& pt) {

        cout << pt.getX() << ", " << pt.getY() << endl;

        return cout;

}

Point operator+(const Point& pt1,const Point& pt2) {

        Point result(pt1.getX() + pt2.getX(), pt1.getY() + pt2.getY());

        return result;

}

int main() {

        Point pt1(1, 2);

        cout << "CntObj: " << pt1.getCntObj() << endl;

        Point* pPt;

        cout << "CntObj: " << pt1.getCntObj() << endl;

        Point* list = new Point[5]; //동적할당 5개의 개체가 형성

        cout << "CntObj: " << list[0].getCntObj() << endl;

        cout << "Before delete[]" << endl;

        delete[] list;

        cout << "After delete[]" << endl;

        Point pt2(10, 20);

        Point pt3(100, 200);

        pt1 = pt2 + pt3; // 왜 9?? pt2,pt3,+ 총 3개가 더 증가함

        cout << "CntObj: " << pt1.getCntObj() << endl;

        SpyPoint spy;

        spy.hacking(pt1);

        spy.hacking(pt2);

        spy.hacking(pt3);

        cout << "Exit program" << endl;

        return 0;

}