c++ - 指向外部类 C++

标签 c++ pointers scope hierarchical-data

在这里,我试图创建第 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/

相关文章:

c++ - 帮助?为什么输出是这样的?

c++ - 为什么我不能拥有指向与成员变量具有相同类型指针的对象的指针?

JavaScript 数组和作用域

c - 关于 C 指针范围

php - Laravel - 如何知道关系表中是否存在该属性

c++ - 计算着色器 OpenGL 写入纹理

c++ - 资源管理器上下文菜单的 Shell 扩展,图标打破了经典 Windows 设计中的对齐方式

c++ - 我可以创建一个谓词来接受函数和仿函数作为参数吗?

go - go中“无法分配给取消引用”是什么意思?

c - 为什么将 const 值分配给指针时出现可疑指针转换警告?