2012-09-04 4 views
0

여기에서 N 번째 계층 구조를 만들려고하지만 내부 클래스의 외부 클래스를 가리키고 액세스 위반 오류가 발생합니다. 그러나 후자의 버전이 작동합니다.외부 클래스 C++을 가리키는

내 실수는 무엇입니까? 새로 생성 된 inner-loops의 범위에 관한 것입니까? 그러나 그것들은 문제가되어서는 안된다.

// atom.cpp : Defines the entry point for the console application. 
// 

#include "stdafx.h" 
#include<iostream> 
#include<stdlib.h> 

class a 
{ 
public: 
    int x; 
    a * inner; 
    a * outer; 
    a(int n) //creates an inner a 
    { 
     n--; 
     x=n;  
     if(n>0){inner=new a(n);}else{inner=NULL;} 
     inner->outer=this;//Unhandled exception at 0x004115ce in atom.exe: 0xC0000005: 
          //Access violation writing location 0x00000008. 
    } 

}; 

int main() 
{ 
    a * c=new a(5); 
    a * d=c; 
    while((d->inner))  //would print 4321 if worked 
    { 
     std::cout<<d->x; 
     d=d->inner; 
    } 
    getchar(); 
    delete c; 
    d=NULL; 
    c=NULL; 
    return 0; 
} 

하지만이 작동합니다 : 당신은

// atom.cpp : Defines the entry point for the console application. 
// 

#include "stdafx.h" 
#include<iostream> 
#include<stdlib.h> 

class a 
{ 
public: 
    int x; 
    a * inner; 
    a * outer; 
    a(int n) //creates an inner a 
    { 
     n--; 
     x=n;  
     if(n>0){inner=new a(n);inner->outer=this;}else{inner=NULL;} 
     //works without error 
    } 

}; 

int main() 
{ 
    a * c=new a(5); 
    a * d=c; 
    while((d->inner))  //prints 4321 
    { 
     std::cout<<d->x; 
     d=d->inner; 
    } 
    getchar(); 
    delete c; 
    d=NULL; 
    c=NULL; 
    return 0; 
} 

생각하십니까 그들은 모두 난 그냥 C를 삭제 자동 h 제하십시오 있습니까?

+0

이런 종류의 자동 * 삭제 기능이 의심 스러우면 어떻게 될까요? –

+0

그들은 NULL에 도달 할 때까지 자동으로 destruting을 시작합니까? 아마도? –

답변

4

당신은이 작업을 수행 할 때 :

if(n>0) 
{ 
    inner=new a(n); //first n is 4, then 3,2,1 and then 0 
} 
else 
{ 
    inner=NULL; 
} 
inner->outer=this; 

n>0 결국 (5 호출에) 유지되지 않습니다 조건, 때를 이렇게 innerNULL 될 것입니다, 그리고 당신이 정의되지 않은 동작 (과 충돌)에 꼬맹 그것을 역 참조하려고 시도합니다 (inner->outer).

1

이 줄 :

inner->outer=this 

필요가 inner = new a(n) 라인 후 if (n > 0) 지점 내부 될, 예를 들면 : 당신은 널 포인터 예외를 보장 할 때 n == 0 서면으로

a(int n) : inner(0), outer(0) // set data members here 
{ 
    x = --n; 
    if (n > 0) { 
     inner = new a(n); 
     inner->outer = this; 
    } 
} 

, NULL->outer = this으로 설정하려고 할 때

+0

답변 해 주셔서 감사합니다. –

관련 문제