Domanda

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.

È stato utile?

Soluzione

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

Altri suggerimenti

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_;
};
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top