在这里,我试图创建第 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就自动删除了吗?
最佳答案
当你这样做时:
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 次调用时),因此 inner
将为 NULL
,然后您会运行当您尝试取消引用它时(inner->outer
)进入未定义的行为(和崩溃)。
关于c++ - 指向外部类 C++,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12271454/