c++ - 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;
}
解决方案
你的代码有很多问题:
- 在
Main.cpp
您取消引用 NULL 指针:node->DosyaOku();
,但节点为 NULL。这是未定义的行为。 - 你有同样的问题
NodeList.cpp
- 您正在使用
malloc
inNode.cpp
并且您可能应该使用 anew
代替(阅读此处),并且您应该考虑如何free
/delete
那个指针。 Create
in有一个立即被覆盖的Node.cpp
参数,看起来像一个错误。
推荐阅读
- spring-boot - 是否可以使用 spring-cloud-config 服务器的端点下载文件夹/目录?
- javascript - 如何使用基于标准的传统 forloop 在数组之间插入项目?
- python - Python Django,无法导入 Django?
- python-3.x - 查找列表项是否在文件名中
- java - 有没有办法将 CompletableFuture 放入循环中?
- python - 如何使用gsutil删除gcs中的多个文件,除了1
- javascript - 如何正确解构这个 JavaScript
- python - 在 Python 中展示行之间的百分比增加/百分比变化
- javascript - 未捕获的引用错误:提示未定义
- laravel - Laravel 队列循环处理