在這裏,我試圖創建一個第N級別的層次結構,但不讓我指向內部類的外部類並獲取訪問衝突錯誤。但後者版本工作。指向外層C++
我的錯誤是什麼?這是關於新創建的內部循環的範圍嗎?但是它們是在課堂內部創建的,所以它不應該成爲問題嗎?
// 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;
}
你覺得一切又都自動deletet當我剛剛刪除C?
你的經驗會導致懷疑這種* auto * -deletion功能? –
他們開始自動destruting,直到他們到達NULL?也許? –