Question

folks. Here's my piece of code:

class Solar_system
{
    public:

    Solar_system()
    {
        planet_no = 5;
    }

    int planet_no;
    int planet[planet_no];
};

Error given: invalid use of non-static data member Solar_system::planet_no

Any help would be greatly appreciated.

Was it helpful?

Solution

I am assuming this is in C++.

When creating an array at run time it should be dynamically allocated. Like this:

http://www.cplusplus.com/doc/tutorial/dynamic/

So you would create a pointer in the class and then set the array up:

int * planet;
int planet_no;
Solar_system()
{
    planet_no = 5;
    planet = new int[planet_no];
}

OTHER TIPS

Instead of doing your own memory management, use a suitable container. For example, std::vector.

class Solar_system {
public:

    Solar_system()
    {
        planets_.resize(5);
    }

    std::vector<int> planets_;
};
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top