C++ Class Object


C++에서 클래스와 객체는 객체 지향 프로그래밍(Object-Oriented Programming, OOP)의 핵심 요소입니다. 클래스는 데이터와 이를 처리하는 함수(메서드)를 하나로 묶는 사용자 정의 데이터 타입이며, 객체는 클래스의 인스턴스입니다. 여기서는 클래스 정의, 생성, 접근 지정자, 생성자, 소멸자, this 포인터 등을 자세히 설명하겠습니다.

클래스와 객체

클래스 정의 및 객체 생성

클래스는 class 키워드를 사용하여 정의합니다. 클래스는 멤버 변수와 멤버 함수로 구성됩니다. 객체는 클래스로부터 생성된 인스턴스입니다.

#include <iostream>

class Person {
public:
    std::string name;
    int age;

    void display() {
        std::cout << "Name: " << name << ", Age: " << age << std::endl;
    }
};

int main() {
    Person person1; // 객체 생성
    person1.name = "John";
    person1.age = 30;
    person1.display();

    return 0;
}

접근 지정자

접근 지정자는 클래스 멤버의 접근 권한을 설정합니다. 주요 접근 지정자는 public, private, protected입니다.

  • public: 어디서든 접근 가능
  • private: 클래스 내부에서만 접근 가능
  • protected: 클래스 내부 및 상속받은 클래스에서만 접근 가능
#include <iostream>

class Person {
private:
    std::string name;
    int age;

public:
    void setName(std::string n) {
        name = n;
    }

    void setAge(int a) {
        age = a;
    }

    void display() {
        std::cout << "Name: " << name << ", Age: " << age << std::endl;
    }
};

int main() {
    Person person1;
    person1.setName("John");
    person1.setAge(30);
    person1.display();

    return 0;
}

생성자와 소멸자

생성자는 객체가 생성될 때 호출되며, 객체를 초기화합니다. 소멸자는 객체가 소멸될 때 호출되며, 자원을 해제합니다.

  • 생성자: 클래스 이름과 동일한 이름을 가지며 반환 타입이 없습니다.
  • 소멸자: 클래스 이름 앞에 ~ 기호가 붙으며 반환 타입이 없습니다.
#include <iostream>

class Person {
private:
    std::string name;
    int age;

public:
    // 기본 생성자
    Person() {
        name = "Unknown";
        age = 0;
    }

    // 매개변수가 있는 생성자
    Person(std::string n, int a) {
        name = n;
        age = a;
    }

    // 소멸자
    ~Person() {
        std::cout << "Destructor called for " << name << std::endl;
    }

    void display() {
        std::cout << "Name: " << name << ", Age: " << age << std::endl;
    }
};

int main() {
    Person person1; // 기본 생성자 호출
    person1.display();

    Person person2("John", 30); // 매개변수가 있는 생성자 호출
    person2.display();

    return 0;
}

this 포인터

this 포인터는 객체 자신을 가리킵니다. 멤버 함수 내에서 사용되며, 객체의 멤버에 접근하거나 다른 멤버 함수를 호출할 때 유용합니다.

#include <iostream>

class Person {
private:
    std::string name;
    int age;

public:
    Person(std::string name, int age) {
        // this 포인터를 사용하여 멤버 변수와 매개변수를 구분
        this->name = name;
        this->age = age;
    }

    void display() {
        std::cout << "Name: " << name << ", Age: " << age << std::endl;
    }
};

int main() {
    Person person1("John", 30);
    person1.display();

    return 0;
}

상속

상속은 기존 클래스의 특성을 새로운 클래스가 물려받는 것을 의미합니다. 기본 클래스(부모 클래스)로부터 파생된 클래스(자식 클래스)를 정의할 수 있습니다.

#include <iostream>

class Person {
protected:
    std::string name;
    int age;

public:
    Person(std::string name, int age) {
        this->name = name;
        this->age = age;
    }

    void display() {
        std::cout << "Name: " << name << ", Age: " << age << std::endl;
    }
};

// Student 클래스는 Person 클래스를 상속받음
class Student : public Person {
private:
    int studentID;

public:
    Student(std::string name, int age, int studentID) : Person(name, age) {
        this->studentID = studentID;
    }

    void display() {
        Person::display(); // 부모 클래스의 display 함수 호출
        std::cout << "Student ID: " << studentID << std::endl;
    }
};

int main() {
    Student student1("Alice", 20, 12345);
    student1.display();

    return 0;
}

예제 프로그램

아래는 클래스와 객체, 생성자와 소멸자, this 포인터, 상속 등을 모두 사용하는 예제 프로그램입니다.

#include <iostream>

class Person {
protected:
    std::string name;
    int age;

public:
    // 기본 생성자
    Person() {
        name = "Unknown";
        age = 0;
    }

    // 매개변수가 있는 생성자
    Person(std::string name, int age) {
        this->name = name;
        this->age = age;
    }

    // 소멸자
    ~Person() {
        std::cout << "Destructor called for " << name << std::endl;
    }

    void display() {
        std::cout << "Name: " << name << ", Age: " << age << std::endl;
    }
};

// Student 클래스는 Person 클래스를 상속받음
class Student : public Person {
private:
    int studentID;

public:
    // 매개변수가 있는 생성자
    Student(std::string name, int age, int studentID) : Person(name, age) {
        this->studentID = studentID;
    }

    void display() {
        Person::display(); // 부모 클래스의 display 함수 호출
        std::cout << "Student ID: " << studentID << std::endl;
    }
};

int main() {
    // 기본 생성자 호출
    Person person1;
    person1.display();

    // 매개변수가 있는 생성자 호출
    Person person2("John", 30);
    person2.display();

    // 상속된 클래스의 생성자 호출
    Student student1("Alice", 20, 12345);
    student1.display();

    return 0;
}

이 예제는 클래스와 객체 생성, 접근 지정자, 생성자와 소멸자, this 포인터, 상속 등을 모두 보여줍니다. C++에서 객체 지향 프로그래밍을 이해하고 활용하는 데 도움이 될 것입니다.


Leave a Reply

Your email address will not be published. Required fields are marked *