首页 > 解决方案 > C++一个类使用其他类

问题描述

我正在尝试将 Node 定义为 NodeList 类,并存储它。

我试过的是:

Try()函数中,我定义了一个像Node *node = malloc...This 工作正常的节点。但是,如果我使用我在类中定义的节点,例如node = malloc...这一行,则会出现运行时错误。我不明白这两者有什么区别。

以下是课程:

节点.hpp

#ifndef NODE_HPP
#define NODE_HPP

class Node{
public:
    int data;
};

#endif

节点.cpp

#include <iostream>
#include "Node.hpp"

using namespace std;

节点列表.hpp

#ifndef NODELIST_HPP
#define NODELIST_HPP

#include "Node.hpp"

class NodeList{
public:
    Node *node;
    void Try();
};

#endif

节点列表.cpp

#include <iostream>
#include "NodeList.hpp"
#include "Node.hpp"

using namespace std;

void NodeList::Try(){
    //This works (doesn't give error):
    //Node *node = (Node*)malloc(sizeof(Node));

    //But I use the node I defined in class here and this line gives runtime error:
    node = (Node*)malloc(sizeof(Node));
}

主文件

#include <iostream>
#include "NodeList.hpp"

using namespace std;

int main()
{
    NodeList *node = NULL;
    node->Try();
    system("PAUSE");
    return 0;
}

标签: c++classpointers

解决方案


你的代码有很多问题:

  1. Main.cpp您取消引用 NULL 指针:node->DosyaOku();,但节点为 NULL。这是未定义的行为。
  2. 你有同样的问题NodeList.cpp
  3. 您正在使用mallocinNode.cpp并且您可能应该使用 anew代替(阅读此处),并且您应该考虑如何free/delete那个指针。
  4. Createin有一个立即被覆盖的Node.cpp参数,看起来像一个错误。

推荐阅读