简体   繁体   中英

got error while compiling memory allocation code of c++ program

i'm writing a memory allocation program in c++ but got an error in the program.
i can't understand what is happening.
Please help.

#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;
}

also i'm new to c++

private:
    void Test(){
        m_ptr = new int(4);
    }

should be

public:
    Test(){
        m_ptr = new int(4);
    }

There's no return type on a constructor, and if you want to use it in main it should be public.

And

    ~Test(class Test){
        cout<<"Object gets destroyed..";
    }

should be

    ~Test(){
        cout<<"Object gets destroyed..";
    }

There are no parameters for a destructor and they should (almost always) be public.

Also

delete [] ptr;

should be

delete ptr;

If you allocate with new then you deallocate with delete . Only if you allocate with new[] do you deallocate with delete[] .

There's a lot of basic syntax errors in a very small program. Whatever source you are looking at to learn the structure of a C++ program cannot be very good. It might be worth spending some time practicing simpler topics before doing memory allocation (which is a very complex subject),

Thanks to dvix and user for helping me spot additional problems in the code.

Your constructors and destructors (that are called) should be public not private .

Also, destructors don't take any arguments. It should be

~Test() {
    cout<<"Object gets destroyed..";
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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