c++ - 编译c++程序的内存分配代码时出错
问题描述
我正在用 C++ 编写内存分配程序,但程序中出现错误。
我不明白发生了什么。
请帮忙。
#include<iostream>
using namespace std;
class Test{
int *m_ptr;
private:
void Test(){
m_ptr = new int(4);
}
~Test(class Test){
cout<<"Object gets destroyed..";
}
};
int main(){
Test *ptr = new Test();
delete [] ptr;
}
我也是 C++ 新手
解决方案
private:
void Test(){
m_ptr = new int(4);
}
应该
public:
Test(){
m_ptr = new int(4);
}
构造函数没有返回类型,如果你想在其中使用main
它应该是公共的。
和
~Test(class Test){
cout<<"Object gets destroyed..";
}
应该
~Test(){
cout<<"Object gets destroyed..";
}
析构函数没有参数,它们应该(几乎总是)是公共的。
还
delete [] ptr;
应该
delete ptr;
如果您使用 分配,new
那么您使用 取消分配delete
。仅当您分配 withnew[]
时,您才会取消分配 with delete[]
。
在一个非常小的程序中有很多基本的语法错误。无论您正在寻找什么资源来学习 C++ 程序的结构,都不是很好。在进行内存分配(这是一个非常复杂的主题)之前,可能值得花一些时间练习更简单的主题,
感谢 dvix 和用户帮助我发现代码中的其他问题。
推荐阅读
- angular - Stencil 全局样式在发布包并在 Angular 中使用后未应用
- react-native - useEffect 和 useState 未在 fetch 中设置值
- android - 在视图寻呼机 2 中禁用垂直滚动
- excel - 通过 PowerShell 将 .odc 文件导入 Excel
- tensorflow - 在 Keras 中使用空洞卷积
- tensorflow - 在 Keras 中使用空洞卷积
- java - 无法启动 bean 'replyingTemplate';嵌套异常是 java.lang.IllegalStateException:Error handler is not compatible with the message listener
- python - 'NoneType' 对象不可迭代 - 哪里有错误?
- c# - 单击重置按钮 C# 时,我的计时器未重置
- wso2 - 无法根据 WSO2 API 管理器中的消息中介策略调用动态端点/URL