2011-03-10 7 views
1

이 두 생성자의 차이점은 무엇입니까? x(px), y(py) 무엇을이 두 생성자의 차이점은 무엇입니까?

int x, y; //position 

BasePoint(int px, int py) : x(px), y(py) {} 

int x, y; //position 

BasePoint(int px, int py) 
{ 
    x = px; 
    y = py; 
} 

라고? 그리고 언제 이런 유형의 변수 초기화를 사용합니까?

감사합니다.

답변

6

첫 번째 initialization-list를 사용 초기화를 수행하고, 두 번째는 할당 연산자를 사용 할당하고있다.

첫 번째 것이 좋습니다!

BasePoint(int px, int py) : x(px), y(py) {} 
          ^^^^^^^^^^^^^ this is called initialization-list! 

는 FAQ를 읽어

초기화 목록 : Should my constructors use "initialization lists" or "assignment"?

의 FAQ 대답은 시작됩니다. 실제로 생성자는 초기화 목록에있는 모든 구성원 개체를 규칙으로 초기화해야합니다. 단 한가지 예외는 입니다. [...]

답을 읽으십시오.

3

x (px), y (py) 란 무엇입니까?

이러한 것을 이니셜 라이저 목록이라고합니다. 실제로 수행하는 작업은 px의 값을 xpy ~ y에 복사하는 것입니다.

용도 : 생성자의 인수가 기본 클래스 생성자에 전달 될 수있는 파생

class foo 
{ 
    private: 
    int numOne ; 

    public: 
    foo(int x):numOne(x){} 
}; 

class bar : public foo 
{ 
    private: 
    int numTwo; 

    public: 
    bar(int numTwo): foo(numTwo), // 1 
         numTwo(numTwo) // 2 
    {} 
}; 

bar obj(10); 

1. 알 수 있습니다.

2.이 경우 컴파일러는 어떤 것이 인수이고 어떤 것이 멤버 변수인지를 결정할 수 있습니다.

bar::bar(int numTwo) : foo(numTwo) 
{ 
    this->numTwo = numTwo; // `this` needs to be used. And the operation is called assignment. There is difference between initialization and assignment. 
} 
여기
0
BasePoint(int px, int py) : x(px), y(py) {} 

u는 이렇게 구축 된 객체가 체내 이동 및 저장 values.it 그 시작되지 않고 초기화 목록 을 사용하는 -이 다음 생성자에서 수행 될 필요가있는 경우했다 생성자 본문에 입력하지 않음으로써 시간.

또 다른 사용은 파생 클래스 생성자를 호출 할 때입니다.

어디

new derivedclass(a,b,c) 

처럼 문을 사용하고이

derivedclass(int x,int y,int z):baseclass(a,b),h(z){} 
을 쓸 수있는 경우
관련 문제