새소식

🏫 School/[23-2] 객체지향프로그래밍

[C++] Software Component (2)

  • -

Pass by Reference

[const]

- 함수에서 어떤 객체를 불러올 때, call by reference를 이용하면 값이 바뀔 수 있음
- 값이 바뀌며 코드가 꼬이는 것을 방지하기 위해 const 사용

Pass to Object

[*]

pointer를 배울 때 우리가 얻고자 하는 값으로 이동하도록 하는 operator라고 배움
=> class 변수에 사용하면, class 자체를 의미 & 멤버 변수에 접근 가능

[->]

pointer 변수 (주소) -> 변수 
로 표현하면 해당 pointer 주소로 가서 변수값울 읽어줄래? 라는 의미가 됨
따라서, (*ptr2).x=1.0과 ptr2->x=1.0은 같은 의미

[new & delete]

class 변수에 대해서도 동적 할당 가능
메모리 효율을 높일 수 있는 방법으로 사용

[주의 사항]
동적할당을 해제하는 것을 항상 주의할 것
delete를 하지 않을 거면 그냥 쓰지도 말자

[this Pointer]

한 class 안에서 자기 자신에 대한 pointer를 사용하고 싶을 때, this를 이용

Overloading

같은 함수 이름, 또는 연산자를 사용해 하나 이상을 정의할 수 있는 방법

[Function Overloading]

연산자 overloading과 유사한 방식

[Operator Overloading]

Point operator +(Point& pt){
        Point result(this->x + pt.x, this->y + pt.y);
        return result;
    }

point 객체 끼리 연산을 진행하고 싶을 때 사용 => 특정 operator에 대해 동작하는 연산자를 만들어낼 수 있음

Static Members

모든 객체가 공유하고 접근할 수 있는 데이터와 함수를 의미
각각 객체가 만들어질때, static으로 전달되는 멤버 변수는 초기화 할 수 없음
:: 를 이용 하여 초기화 해줘야 함

Structure

Class와 유사하지만, defualt로 public으로 작동함

Friend Relationship

[Friend Function]

서로 다른 두 class가 Friend 관계라고 인정하면,
(A가 외부의 B class와 Friend관계라 하면) B는 A의 모든 정보의 접근 및 사용이 가능함
Friend는 단방향 관계로, A가 B의 모든 정보를 사용할 수는 없음

Destructor (소멸자)

객체의 할당 해제시, 자동으로 1회 호출되는 함수
~class명 으로 생성 (입력값과 리턴값 모두 존재하지 않음)


//예시 코드

#include <iostream>
using namespace std;

class Point {
private:
	int x;
	int y;
	static int numCreatedObjects;
public:
	Point (int _x = 0, int _y = 0) :x(_x), y(_y) {
		numCreatedObjects++;
	}
	int getX() const { return this->x; }
	int getY() const { return this->y; }
	void setXY(int _x, int _y) { x = _x; y = _y; }

	//pt2.+(pt3) == pt2 + pt3
	Point operator+(const Point& pt) {
		Point result(this->x + pt.x, this->y + pt.y);
		return result;
	}

	//a = b = c = d; 왼쪽에서 오른쪽으로 연속적으로 계산 가능
	Point operator=(const Point& pt) {
		this->x = pt.x;
		this->y = pt.y;
		return *(this);
	}

	static int getNumCreatedObject() { return numCreatedObjects };
	friend void print(const Point& pt);
	friend ostream& operator<<(ostream& cout, const Point& pt);
	friend class Spy; //Point class는 Spy를 친구로 인정
};

//static 멤버 변수 초기화
int Point::numCreatedObjects = 0;

void print(const Point& pt)
{
	cout << pt.x << ", " << pt.y << endl;
}

void print(int a) {
	cout << a << endl;
}

ostream& operator<<(ostream& cout, const Point& pt) {
	cout << pt.x << ", " << pt.y;
	return cout;
}

class Spy {
public:
	void hack_all_info(const Point& pt) {
		cout << "Hacked by Spy" << endl;
		cout << "x: " << pt.x << endl;
		cout << "y: " << pt.y << endl;
		cout << "numCreatedObj: " << pt.numCreatedObjects << endl;
		cout << endl;
	}
};

int main() {
	//pass by ref & const
	Point pt1(1, 2);
	print(pt1);
	cout << pt1.getNumCreatedObject() << endl;
	cout << endl;

	//포인터 동적 할당
	Point* pPt = new Point(10, 20); //pointer: (.)대신 ->로 access
	cout << (*pPt).getX() << ", " << (*pPt).getY() << endl; //비추
	cout << pPt->getX() << ", " << pPt->getY() << endl; //추천
	cout << pt1.getNumCreatedObject() << endl;
	cout << endl;

	//연산자 오버로딩(연산자도 모두 함수)
	int a = 2 + 3; //+(2, 3)
	Point pt2(10, 20), pt3(30, 40);
	Point pt4 = pt2 + pt3;
	cout << pt2 << endl;
	cout << pt3 << endl; 
	cout << pt4 << endl;
	cout << pt1.getNumCreatedObject() << endl;
	cout << endl;

	//friend ft
	Spy spy;
	spy.hack_all_info(pt1);
	spy.hack_all_info(pt4);

	return 0;
}

'🏫 School > [23-2] 객체지향프로그래밍' 카테고리의 다른 글

[C++] Generic Programming  (4) 2023.12.03
[C++] Inheritance (상속)  (0) 2023.11.16
[C++] Software Component (1)  (0) 2023.11.16
[C++] Lab #01&02  (0) 2023.10.20
[C++] Pointer & Vector & Array  (0) 2023.10.16
Contents

포스팅 주소를 복사했습니다

이 글이 도움이 되었다면 공감 부탁드립니다.