nakka soft world !

this 본문

프로그래밍언어/C++

this

nakka 2017. 3. 19. 01:04
728x90

this.

1. 개념


class Point

{

private:

int x;

int y;

public:

void set(int a, int b)  // void (Point* const this, int a, int b)

{

x = a;  // this->x = a;

y = b;  // this->y = b;

}

};

int main()

{

Point p1;

Point p2;


p1.set(10, 20);  // set( &p1, 10, 20) 으로 컴파일되어 이 함수가  p1꺼라는것 을 알 수 있게 함.

}

x가 p1꺼인지 p2꺼인지 알 수 없음. 따라서 컴파일러가 컴파일되는 시점에 this call로 변경됨.


class Point

{

private:

int x;

int y;

public:

void foo()

{

cout << this <endl;

}

};

int main()

{

Point p1;

Point p2;


p1.foo();

cout << &p1 << endl;


p2.foo();

cout << &p2 << endl;

}


2. 활용

class Point

{

private:

int x;

int y;

public:

void set(int x, int y)

{

// x : 함수 인자의 x

this->x = x;

this->y = y;

}

};

int main()

{

Point p;

p.set(10, 20);

}


// this를 리턴 하는 함수

class Car

{

private :

int color;

public:

Car* Go1() { return this; }

Car Go2() { return *this; )  // 복사본 리턴, 임시객체가 생성됨

};


int main()

{

Car c;

c.Go1()->Go1()->Go1()->;

c.Go2().Go2().Go2();


cout << "A" << "B" << "c" << endl;  //cout 이 this를 리턴 하는 구조 임.

}


3. this주의사항


class Point

{

private:

int x;

int y;

public:

static void foo()

{

cout << this << endl;  // static 멤버 함수에서는 this를 사용할 수 없다. error.

// this는 객체의 주소임. static은 객체가 없이 동작함.

}

};

int main()

{

Point::foo();

}




728x90

'프로그래밍언어 > C++' 카테고리의 다른 글

cout & ostream  (0) 2017.03.19
연산자 재정의 개념  (0) 2017.03.19
상수 멤버 함수 (const member function)  (0) 2017.03.19
정적 멤버 데이터 (static member data)  (0) 2017.03.17
Object Copy  (0) 2017.03.17
Comments