2013-03-13 3 views
1
#include <iostream> 

class FooParent 
{ 
    public: 
     FooParent(int* new_p_bar) 
     { 
      p_bar = new_p_bar; 
     } 
    public: 
     int* p_bar; 
}; 

class FooChild : public FooParent 
{ 
    public: 
     int bar; 
    public: 
     FooChild(int new_x) 
     :FooParent(&bar) 
     ,bar(new_x) \\ point of concern 
      {} 
}; 

int main() 
{ 
    FooChild foo(8); 
    std::cout << foo.bar << std::endl; 

} 

위 예제는 내가 원하는대로 작동합니다. 포인터 p_barbar에 연결하십시오. 그러나, 내 관심은 생성자가 아직 호출되지 않은 멤버를 가리키고 있다는 것입니다.구성원 개체에 대한 포인터 및 선언 순서

이 코드가 유효 한가, 아니면 표준에 대해 그에 대한 의견이 있습니다. 대안이 아닌 경우.

참고을 : 내 응용 프로그램 bar에서이 어떤 영향을 미칠 않는 객체 Bar (안 int)인가?

+0

생성자가 호출되었을 것입니다. 이니셜 라이저 목록의 순서는 구성 순서와 동일하지 않습니다. 멤버 변수는 클래스의 선언 순서에 따라 초기화됩니다. –

+0

'FooParent'의 c-tor가'Bar'의 주소만을 저장하고'FooParent (& bar)'와'bar (new_x) '사이에 다른 초기화가 없다면 문제가없는 것 같습니다 – borisbn

+4

다른 말로하면 ** 포인터 ** (또는 참조)에서만 작동합니다. 객체의 복사본이 아닙니다. – borisbn

답변

0

봐 조사 :

class FooParent { 
    public: 
     FooParent(int* new_p_bar) 
     { 
      p_bar = new_p_bar; 
      *p_bar = 99; // this has no sense 
     } 
     void set99() { 
      *p_bar = 99; // this - has 
     } 
    public: 
     int* p_bar; 
}; 

class FooChild : public FooParent 
{ 
    public: 
     int bar; 
    public: 
     FooChild(int new_x) 
     :FooParent(&bar) 
     ,bar(new_x) // point of concern 
      {} 
}; 

int main() 
{ 
    FooChild foo(42); 
    std::cout << foo.bar << std::endl; 
    foo.set99(); 
    std::cout << foo.bar << std::endl; 
} 

LWS합니다. (- 중요하지 않습니다 또는 Bar) 다음 아무 문제가 없을 것입니다

나는 FooParent의 생성자 는 외부 int에 대한 포인터를 저장하면 것을 의미한다. 반면에

, 당신이 FooParentbar 복사주지 경우 -이

class FooParent 
{ 
    public: 
     FooParent(Bar new_p_bar) 
     { 
      p_bar = new_p_bar; 
     } 
     void set99() { 
      p_bar = 99; // this - has 
     } 
    public: 
     Bar p_bar; 
}; 

class FooChild : public FooParent 
{ 
    public: 
     Bar bar; 
    public: 
     FooChild(Bar new_x) 
     :FooParent(bar) 
     ,bar(new_x) // point of concern 
      {} 
}; 

int main() 
{ 
    FooChild foo(42); 
    std::cout << foo.bar << std::endl; 
    foo.set99(); 
    std::cout << foo.bar << std::endl; 
} 

LWS처럼.

이것은 작동하지 않습니다. Bar에 복사기 나 할당 연산자가있을지라도

+0

복사 할 때 'FooChild'에 대한 복사 및 복사 지정을 말합니다. 복사 할 때 'FooChild'는 새로 복사 된'Bar'에'p_bar'를 할당합니다. 그게 충분히 좋을 까? – aiao

+0

오아 ... 죄송합니다. 나는 바의 사본 c-tor를 소리내어 생각했다. ..새로 복사 한'Bar'에'p_bar'를 할당하면 아무런 문제가 없습니다. " – borisbn