【问题标题】:Pointing to outer-class C++指向外部类 C++
【发布时间】:2012-09-04 21:14:24
【问题描述】:

在这里,我正在尝试创建第 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 时,你认为它们都是自动删除的吗?

【问题讨论】:

  • 根据您的经验,您会怀疑这种 自动 删除功能吗?
  • 他们开始自动破坏直到达到 NULL?也许?

标签: c++ pointers scope hierarchical-data


【解决方案1】:

当你这样做时:

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&gt;0 最终将不成立(在第 5 次调用时),因此 inner 将是 NULL,然后当您尝试取消引用它时会遇到未定义的行为(和崩溃)(@987654325 @)。

【讨论】:

    【解决方案2】:

    这一行:

    inner->outer=this
    

    需要在if (n &gt; 0) 分支内,在inner = new a(n) 行之后,例如:

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

    正如所写,当n == 0 尝试设置NULL-&gt;outer = this 时,保证会出现空指针异常。

    【讨论】:

      猜你喜欢
      • 2012-04-26
      • 1970-01-01
      • 2011-02-04
      • 1970-01-01
      • 2012-07-20
      • 2021-10-19
      • 1970-01-01
      • 2013-04-18
      • 1970-01-01
      相关资源
      最近更新 更多