전체 글

전체 글

    [C++] 상속과 접근 지정자 (access specifiers)

    [C++] 상속과 접근 지정자 (access specifiers)

    1. 상속과 접근 지정자 (access specifiers) class Base { private: int a; public: int c; }; class Derived : public Base { }; int main() { Derived derv; derv.a = 10; // error derv.c = 10; // ok } 위 코드는 Base를 기반 클래스로 Derived클래스가 상속받았다. 따라서 Derived클래스에는 적혀있진 않지만 a와 c 멤버데이터가 있다. main함수에서 a와 c에 접근하려 하는데 c는 public이라 상관없지만 a는 private으로 외부에서 접근할 수 없으므로 에러가 난다. 그렇다면 다음 코드는 어떨까? class Base { private: int a; public: ..

    [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 포인터

    [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

    [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

    [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

    [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() { ++..