프로그래밍/C++
[C++] 상속
1. 상속 #include #include class Professor { std::string name; int age; int major; }; class Student { std::string name; int age; int id; }; int main() { } 위의 코드에서 멤버 데이터인 name과 age가 중복되는것을 볼 수 있다. ① Student와 Professor의 공통의 특징을 모아서 Person 클래스를 설계한다. #include #include class Person { std::string name; int age; }; class Professor : public Person { int major; }; class Student : public Person { int id; }..
[C++] this 포인터
1. this 포인터 개념 class Point { int x = 0; int y = 0; public: void set(int a, int b) { x = a; y = b; } }; int main() { Point p1; Point p2; p1.set(10, 20); p2.set(30, 40); std::cout 자신을 호출한 객체의 주소를 담고 있다. p1.set(10, 20); 코드를 통해 set함수는 p1의 멤버데이터는 바꿀까 p2의 멤버데이터를 바꿀까? 물론 p1.set이기 때문에 p1의 멤버데이터를 바꿀 것이다. 좀 더 자세히 살펴보면 p1.set(10, 20); 이라는 코드는 컴파일러가 set(&p1, 10, 20); 이라고 전달하게 된다. void set(Point* this, int a..
[C++] const member function
1. 상수 멤버 함수 (const member function) #include class Point { int x, y; public: Point(int a = 0, int b = 0) : x(a), y(b) {} void set(int a, int b) { x = a; y = b; } void print() const { x = 10; std::cout 멤버 데이터의 값을 읽을 수는 있지만 변경할 수는 없다. ③ 상수 멤버 함수를 사용하는 이유 - 중요! => 코드 작성시 안정성 => 상수 객체는 상수 멤버 함수만 호출할 수 있다. 2. 상수 멤버 함수가 필요한 이유 #include class Point { public: int x, y; Point(int a = 0, int b = 0) : x(a)..
[C++] static member function
1. 정적 멤버 함수 (static member function) class Car { int speed; static int cnt; public: Car() { ++cnt; } ~Car() { --cnt; } int getCount() { return cnt; } }; int Car::cnt = 0; int main() { Car c1, c2, c3; c1.getCount(); } static member data는 객체를 생성하지 않아도 메모리에 올라간다. 위의 코드에서는 getCount() 함수를 통해 객체의 개수를 파악하고 있다. 그런데, 객체를 생성하지 않은 상태에서 개수를 파악하고 싶을 때 getCount()를 어떻게 호출할까? static int getCount() { return cnt;..
[C++] static member data
1. 정적 멤버 데이터 (static member data) #include class Car { int speed; int color; public: Car() {} ~Car() {} }; int main() { Car c1; Car c2; Car c3; } ① 객체의 생성과 소멸 => 모든 객체는 생성 될 때 생성자를 호출하고 => 모든 객체는 파괴 될 때 소멸자를 호출한다. ② 객체가 몇 개 생성되었는지 개수를 알고 싶다면 => 생성자에서 변수 값을 +1 => 소멸자에서 변수 값을 -1 ③ 객체의 개수를 관리할 변수가 필요하다. 객체의 개수를 관리할 변수를 만들어보자 #include class Car { int speed; int color; public: int cnt = 0; Car() { ++..
[C++] 객체의 복사 방법
1. 객체의 복사 방법 #include #include class Person { char* name; int age; public: Person(const char* n, int a) : age(a) { name = new char[strlen(n) + 1]; strcpy(name, n); } ~Person() { delete name; } }; int main() { Person p1("kim", 20); Person p2 = p1; } ① 얕은 복사란? (Shallow Copy) => 클래스 안에 포인터 멤버가 있을 때 디폴트 복사 생성자가 => 메모리 자체를 복사하지 않고 주소만 복사 하는 현상 #include #include class Person { char* name; int age; pub..