首页 > 解决方案 > 编译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++ 新手

标签: 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 和用户帮助我发现代码中的其他问题。


推荐阅读