JAVA

C++ 프로그래머 Java 맛보기 #12

aucd29 2013. 9. 26. 21:06
이번엔 내부 변수 쓰는 법이다.

별로 다를게 없긴 하지만 보통의 경우 내부 변수는 C++ 사용자라면은 m_nValue 식으로 사용하기 때문에 크게 문제는 안되는데 (습관이 남아있다면 말이다.) 만약 로컬 변수와 이름이 같을 경우!! 어떻게 해야할까? 즉 아래와 같은 상황이라면은 어떤식으로 처리해야할지?

public class Point {
    public int x = 0;
    public int y = 0;

    //constructor
    public Point(int x, int y) {
    // todo code
}
}

잠시 생각을 하겠다만은...역시나 비슷하다..

public class Point {
    public int x = 0;
    public int y = 0;

    //constructor
    public Point(int x, int y) {
this.x = x;
this.y = y;
    }
}

이렇게 하면 되긴하지만 아무래도 개인 적으로는

public class Point {
    public int _x = 0;
    public int _y = 0;

    //constructor
    public Point(int x, int y) {
public class Point {
    public int _x = 0;
    public int _y = 0;

    //constructor
    public Point(int x, int y) {
_x = x;
_y = y;
}
}
}
}

이렇게 구분을 해주는걸 추천한다.

두 번재로 생성자에서 값을 초기화 하려면 어떻게 해야할까? 하는 생각이 든다. 이번엔C++ 과 비교해보도록 하자.

java
public class Rectangle {
    private int x, y;
    private int width, height;

    public Rectangle(int width, int height) {
        this(0, 0, width, height);
    }
    public Rectangle(int x, int y, int width, int height) {
        this.x = x;
        this.y = y;
        this.width = width;
        this.height = height;
    }
}


c++
class Rectangle
{
public:
Rectangle(int width, int height)
: _x(0)
, _y(0)
, _width(width)
, _height(height)
{
}
private:
int _x, _y;
int _width, _height;
}
코드와 같이 구현이 가능하다.