#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;
}
'Code > C++' 카테고리의 다른 글
[C++](example) class 생성/ friend/ spy (0) | 2019.11.12 |
---|---|
[C++] class 생성/ this pointer/ 함수오버로딩/ 동적할당 (0) | 2019.11.11 |
[C++] (example) private& public/ 계좌만들기/ 분자& 분모 (0) | 2019.11.02 |
[C++] 계좌만들기/ private & public (0) | 2019.11.02 |
[C++] class & object/ private & public (0) | 2019.11.02 |