[c++] 멤버 변수 초기화

클래스 Person에 두 개의 멤버 변수 nameage가 있습니다. 아래의 예시 코드에서 Person 클래스의 생성자를 사용하여 멤버 변수를 초기화할 수 있습니다.

#include <iostream>
#include <string>

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

    // 생성자를 사용하여 멤버 변수 초기화
    Person(std::string n, int a) : name(n), age(a) {}
};

int main() {
    // 객체를 생성하고 멤버 변수를 초기화
    Person person1("John", 25);
    std::cout << "Name: " << person1.name << ", Age: " << person1.age << std::endl;

    return 0;
}

위의 예시 코드에서 Person 클래스의 생성자에서 멤버 변수 nameage를 초기화하기 위해 초기화 리스트(initialization list)를 사용했습니다. 생성자는 객체가 생성될 때 자동으로 호출되며, 이를 통해 멤버 변수를 초기화할 수 있습니다.

이를 통해 멤버 변수 초기화를 보다 효율적으로 수행할 수 있으며 코드의 가독성을 높일 수 있습니다.

참고 자료: