상세 컨텐츠

본문 제목

C++ 생성자 초기화 리스트, const,static변수 등등

Study/C++

by Ha학생 2023. 9. 10. 16:43

본문

안녕하세요. 하학생입니다.

오늘은 생성자 초기화 리스트 등등에 대해 공부를 진행했습니다. 

바로 시작할게요


생성자 초기화 리스트

생성자 초기화 리스트는 c++에서 클래스 멤버 변수를 초기화하는 방법 중 하나로 생성자 함수 내에서 멤버 변수를 초기화하는 데 사용됩니다.

 

ConstructorName(parameter_list) : member1(value1), member2(value2), ... {
    // 생성자 본문
}

생성자 초기화 리스트는 다음과 같은 형식을 가집니다.

 

생성자 초기화리스트의 이점은 멤버 변수가 두 번  초기화하는 것을 방지할 수 있습니다.

또 상수 멤버 변수나 참조 멤버 변수는 반드시 초기화 리스트를 사용하여 초기화를 해야 하기 때문에 사용합니다.

 

#include <iostream>

class MyClass {
private:
    int x;
    double y;

public:
    // 생성자 초기화 리스트 사용
    MyClass(int a, double b) : x(a), y(b) {
        // 생성자 본문 (생략 가능)
    }

    void display() {
        std::cout << "x: " << x << ", y: " << y << std::endl;
    }
};

int main() {
    // 생성자 초기화 리스트를 사용하여 객체 생성
    MyClass obj(42, 3.14);

    obj.display(); // x: 42, y: 3.14

    return 0;
}

생성자 초기화 리스트는 다음과 같이 사용합니다. 

초기화 리스트를 이용하여 초기화 작업이 효율적으로 이루어지고 가독성이 향상됩니다.


const 멤버변수와 static 멤버 변수 

const 멤버 변수

클래스 내에서 const는 상수값을 나타내고 한번 설정하면 변경할 수 없는 변수입니다.

class Circle {
public:
    const double pi = 3.14159265; // const 멤버 변수

    Circle(double radius) : radius(radius) {}

    double getArea() const {
        return pi * radius * radius;
    }

private:
    double radius;
};

다음과 같이 사용합니다.

const는 객체 내부에서 해당 변수의 값을 수정하는 것을 방지합니다. 

 

static 멤버 변수

static 멤버 변수는 클래스의 모든 객체가 공유하는 변수입니다.

모든 인스턴스가 static멤버 변수를 공유합니다.

 

class BankAccount {
public:
    static double interestRate; // static 멤버 변수

    BankAccount(double balance) : balance(balance) {}

    void applyInterest() {
        balance += balance * interestRate;
    }

    static void setInterestRate(double rate) {
        interestRate = rate;
    }

private:
    double balance;
};

double BankAccount::interestRate = 0.05; // static 멤버 변수 초기화

예시 코드입니다.

 


this 포인터

this 포인터는 클래스 멤버 함수 내에서 현재 객체의 주소를 가리키는 포인터입니다. 

this  포인터를 사용하면 클래스 내에서 현재 객체를 가리키고 객체 간의 이름 충돌을 피할 수 있습니다. 

class MyClass {
public:
    void printAddress() {
        std::cout << "Address of this object: " << this << std::endl;
    }
};

int main() {
    MyClass obj1;
    MyClass obj2;
    obj1.printAddress(); // 객체 obj1의 주소 출력
    obj2.printAddress(); // 객체 obj2의 주소 출력
    return 0;
}

예시 코드는 다음과 같습니다.


오늘은 생성자 초기화 리스트 static , const멤버변수 등등에 대해 공부해 봤습니다. 다음에 봬요!

'Study > C++' 카테고리의 다른 글

C++ 백준 10845번  (0) 2023.09.14
C++ 백준 10828번  (0) 2023.09.14
C++ 복사 생성자,소멸자  (0) 2023.09.10
C++ New,Delete, Class  (0) 2023.09.06
C++ 참조자  (0) 2023.09.05

관련글 더보기

댓글 영역