C++/static, this

C++ static and this Keyword

Soul-Learner 2016. 12. 23. 18:41

C++ 프로그래밍, static, this 키워드 사용하기


static 

static 은 클래스의 멤버변수나 멤버함수에 사용할 수 있는 키워드인데, static 을 사용한 변수와 함수는 클래스 변수, 혹은 클래스 함수라고 한다. static 변수는 소속 클래스의 모든 객체가 공유할 수 있는 변수이며 프로그램 실행시에 단 한번만 메모리에 생성되고 더 이상 생성되지 않는다. 이는 일반 변수(non-static 변수)가 객체를 생성할 때마다 메모리에 생성되는 특징과 구별된다.

static 변수는 전역 범위에서 일단 초기화를 한번 해야만 오류가 발생하지 않고 사용할 수 있다.


this

this는 생성자나 인스턴스 멤버함수 안에서 자신이 포함된 객체의 주소를 가진 포인터이다. this는 인스턴스 변수와 파라미터 변수의 이름이 동일한 영역에서는 필수적으로 사용해야만 멤버변수와 지역변수를 구분할 수 있게 된다


static, this를 사용한 예

#include <iostream>
#include <locale>
#include <string>

using namespace std;

class CVector
{
    double x;
    double y;

    public:
    static int cnt;   // static 변수(클래스 변수)
    //CVector(){}
    CVector(double x, double y) {
        this->x = x;   // this는 현재 객체의 포인터
        this->y = y;
        cnt++;
    }

    CVector operator + (CVector& v) {
    	return CVector(x+v.x, y+v.y);
    }

    void printInfo(){
    	wcout << "x=" << x << ", y=" << y << endl;
    }
};

// static 변수는 전역 범위에서 초기화한 후에 사용할 수 있다
int CVector::cnt = 0;

int main()
{
    setlocale(LC_ALL,"");
    wcout << L"C++ 연산자 오버로딩" << endl;

    CVector v1(1,2);
    CVector v2(3,4);

    v1.printInfo();
    v2.printInfo();

    CVector v3 = v1+v2;
    v3.printInfo();

    //현재까지 생성된 CVector 객체의 수를 확인해본다
    wcout << "cnt=" << CVector::cnt << endl;

    return 0;
}