Referencia sin definir en C++

publicado por: Anonymous

Llevo varios días con el mismo error, “referencia a ‘Container::nextId’ sin definir”.

El .h

class Container

friend std::ostream& operator<< (std::ostream &os, const Container& obj);


protected:
    unsigned int id;
    unsigned int value;
    unsigned int weight;
    static unsigned int nextId;
    static const unsigned int kMINWEIGHT = 100;
    static const unsigned int kMINVALUE = 100;

public:
    Container(unsigned int weight, unsigned int value);
    void static resetNextId();
    unsigned int getId() const;
    unsigned int getValue() const;
    unsigned int getWeight() const;
    void setWeight(unsigned int weight);
    void setValue(unsigned int value);

Y la declaración del método donde da error, en el .cc:

void Container::resetNextId(){

    Container::nextId = 1;

}

He buscado mucha información, y parece ser que el error proviene de modificar el atributo nextId, que es static. He probado todo tipo de cosas, pero no logro averiguar como solucionarlo. El error se produce en la línea donde aparece ‘Container::nextId = 1;’

Gracias de antemano, y un saludo.

solución

Los datos estáticos de clase deben ser definidos fuera de la clase:

class Container {

friend std::ostream& operator<< (std::ostream &os, const Container& obj);


protected:
    unsigned int id;
    unsigned int value;
    unsigned int weight;
    static unsigned int nextId;
    static const unsigned int kMINWEIGHT = 100;
    static const unsigned int kMINVALUE = 100;

public:
    Container(unsigned int weight, unsigned int value);
    void static resetNextId();
    unsigned int getId() const;
    unsigned int getValue() const;
    unsigned int getWeight() const;
    void setWeight(unsigned int weight);
    void setValue(unsigned int value);
};

unsigned int Container::nextId = 1;
unsigned int Container::kMINWEIGHT = 100;
unsigned int Container::kMINVALUE = 100;
Respondido por: Anonymous

Leave a Reply

Your email address will not be published. Required fields are marked *