Minwoo Dev.

[C++] this 포인터 본문

C++

[C++] this 포인터

itisminu 2024. 3. 25. 10:36
728x90
반응형
SMALL

this

C++에서 this는 해당 객체 자체를 참조하는 포인터이다.

객체 내에서 본인이 가지고 있는 멤버변수나 멤버 함수에 접근하기 위하여 this를 많이 사용한다.

 

#include <iostream>
using namespace std;

class Score
{
private:
    int schoolNum;
    int score;

public:
    Score(int schoolNum, int score)
    {
        this->schoolNum = schoolNum; // this 사용!!
        this->score = score;  // this 사용!!
    }
    void showInfo()
    {
        cout << "번호 : " << this->schoolNum << endl;
        cout << "점수 : " << this->score << endl;
        cout << endl;
    }
};

int main(void)
{
    Score sc1(1, 80);
    sc1.showInfo();

    Score sc2(2, 95);
    sc2.showInfo();

    return 0;
}

 

 

위 코드를 보면 Score이라는 클래스의 생성자에 인자로 전달되는 변수의 이름과 멤버변수의 이름이 같은 것을 확인할 수 있다.

 

이렇게 이름이 같은 경우에 우리는 멤버변수에 매개변수로 받아온 값을 넣는 것이므로 코드를 작성한다면 아래처럼 작성될 것이다.

Score(int schoolNum, int score)
    {
        schoolNum = schoolNum;
        score = score;
    }

 

위 코드에서 어떤 게 멤버변수를 가리키는지 알 수 있는가 ?

헷갈릴 것이다. 따라서 우리는 this를 사용하여 명확하게 표시할 수 있다.

 

Score(int schoolNum, int score)
    {
        this->schoolNum = schoolNum;
        this->score = score;
    }

 

this는 여기서 생성한 객체 자체를 가리킨다. main 함수에서 sc1으로 객체를 생성했다면 sc1.schoolNum을 가리키는 것이다.

하지만 this 포인터는 "." 이 아니라 "->" 를 사용하여 내부변수와 내부함수에 접근한다.

 

 

 

 

this는 내부변수 뿐만아니라 내부함수도 사용할 수 있다.

#include <iostream>
using namespace std;

class Score
{
private:
    int schoolNum;
    int score;

public:
    Score(int schoolNum, int score)
    {
        this->schoolNum = schoolNum;
        this->score = score;
    }
    void showInfo()
    {
        cout << "번호 : " << this->schoolNum << endl;
        cout << "점수 : " << this->score << endl;
        cout << endl;
    }
    void EditScore(int edScore)
    {
        this->score = edScore;
        cout << "-----변경 결과-----" << endl;
        this->showInfo();  //this를 사용하여 내부함수 호출
    }
};

int main(void)
{
    Score sc1(1, 80);
    sc1.showInfo();

    Score sc2(2, 95);
    sc2.showInfo();

    sc1.EditScore(70);

    return 0;
}

 

 

위 코드에서는 this를 사용하여 내부 함수인 showInfo를 호출하고 있다.

main함수에서 sc1.EditScore(70)을 통해 점수를 70으로 바꾸고, 변경 결과를 내부 함수인 ShowInfo를 불러와 나타내는 것이다.

 

내부 함수도 this-> 내부함수 의 형태로 사용하면 된다.

 

결과

 

728x90
반응형
LIST