在这里,我正在尝试创建第 N 级层次结构,但不允许我指向内部类的外部类并获得访问冲突错误。但后一个版本有效。
我的错误是什么?这是关于新创建的内部循环的范围吗?但是它们是在类中创建的,所以应该不是问题吗?
// 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 时,您认为它们都是自动删除的吗?