繁体   English   中英

具有struct的C ++链表

[英]C++ Linked Lists with struct

我是C ++的新手,与链接列表有关,我不知道为什么它不起作用,需要教授帮助:O)

这是我的.h

#ifndef UnCube_H
#define UnCube_H

using namespace std;

class ACube{
  public:
         ACube();
         struct Thecube;
  private:
          void PrintList();

  };
#endif

我的ACube.cpp

#include <iostream>
#include "ACube.h"


ACube::ACube(){

};
struct Thecube{
   int base;
   int cube;
   Thecube * next ;
};


void ACube::PrintList(){
};

最后是我的main.cpp

#include <cstdlib>
#include <iostream>
#include "ACube.h"

using namespace std;

int main()
{
ACube * temp;
temp = (ACube*)malloc(sizeof(ACube));
for (int inc=1; inc <=20 ; inc++){

    temp->ACube->nombrebase = inc;
    temp->cube = inc*inc*inc;
}
system("PAUSE");
return EXIT_SUCCESS;
}               

一切工作正常,但是当我添加这些行时:

    temp->ACube->nombrebase = inc;
    temp->cube = inc*inc*inc;

我添加错误说:'类ACube'没有名为'TheCube'的成员'类ACube'没有名为'cube'的成员

有人可以帮我,因为我想创建我的列表并用数字填充多维数据集。 我想用这东西。 在印刷品中

也许有人可以教我什么地方出了问题以及如何去做!

谢谢你的帮助

您无需在班级内部拥有结构。

#ifndef UnCube_H
#define UnCube_H

using namespace std;

class ACube{
  public:
    ACube();
    int base;
    int cube;
    ACube * next ;
  private:
          void PrintList();

  };
#endif

ACube.cpp

#include <iostream>
#include "ACube.h"


ACube::ACube(){

};

void ACube::PrintList(){
};

另外,此字符串是错误的:

temp->ACube->nombrebase = inc;

它应该只是:

temp->base = inc;

最后但并非最不重要的一点是,此代码不会创建链接列表,因为您不会对ACube :: next指针执行任何操作。

您的代码中有很多可怕的问题,我建议您在编写链表之前应该学习更多的C ++知识。

1.什么是nombrebase

我想没人能回答。

2.您必须通过new关键字而不是malloc分配C ++类。

new不仅调用分配,还调用类构造函数,而malloc仅分配。

3. Thecube应该在ACube定义

由于main()中的代码引用Thecube类中的成员cube ,因此main()必须知道它是什么。

4. ACube类中的next成员是一个指向什么的指针?

没有初始化的指针指向什么? 您应该在构造函数中将其初始化,然后在析构函数中销毁它。

5. temp->ACube

ACube是类类型,您可以访问成员对象,但不能访问类型。

6.永远不要在标题文件中使用命名空间

这会使头文件的客户端发生名称冲突。

以下是更正的代码。 只是没有编译错误和运行时错误,但这不是链表:

ACube.h

#ifndef UnCube_H
#define UnCube_H

class ACube{
public:
    struct Thecube
    {
        int base;
        int cube;
        Thecube * next;
    };


    ACube();
    ~ACube();
    Thecube *next;

private:
    void PrintList();

};
#endif

ACube.cpp

ACube::ACube()
: next(new Thecube)
{

}

ACube::~ACube()
{
    delete next;
}

void ACube::PrintList(){
}

main.cpp

#include <cstdlib>
#include <iostream>
#include "ACube.h"

using namespace std;

int main()
{
    ACube * temp;
    temp = new ACube;
    for (int inc = 1; inc <= 20; inc++)
    {
        temp->next->base = inc;  // <-- This is not linked list, you shall modify.
        temp->next->cube = inc*inc*inc;  // <-- This is not linked list, you shall modify.
    }
    system("PAUSE");
    return EXIT_SUCCESS;
} 

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM