unresolved references when using static

Collapse
This topic is closed.
X
X
 
  • Time
  • Show
Clear All
new posts
  • Tony Johansson

    #1

    unresolved references when using static

    Hello!

    I have the two classes Outdoors and Animal and a main. The Outdoors class is
    a singleton.
    The Outdoors is in outdoors.h and Animal is in animal.h. I'm using .h file
    just for being easy to show you.
    You can see the definition of the classes below.

    Now to my problem in the instance method of class Outdoors I call
    the static method makeAnimal(); which have only one statement and that is
    this temp = new Animal();
    The definition of temp is located in the private section and looks like
    static Animal* temp;
    When I have this temp = makeAnimal() statement it will not compile. I get
    the following errors.

    Compiling...
    start.cpp
    Linking...
    start.obj : error LNK2001: unresolved external symbol "private: static class
    Animal * Outdoors::temp" (?temp@Outdoors @@0PAVAnimal@@A )
    Debug/slask.exe : fatal error LNK1120: 1 unresolved externals
    Error executing link.exe.

    Why can't I instansiate an object of class Animal.?

    start.cpp
    *******
    #include "outdoors.h "
    int main()
    {
    Outdoors* base = Outdoors::insta nce();
    return 0;
    }

    outdoors.h
    *********
    class Outdoors
    {
    public:

    static Outdoors* instance()
    {
    if (onlyInstance == 0)
    {
    onlyInstance = new Outdoors();
    makeAnimal();
    }
    return onlyInstance;
    }
    private:
    static Animal* temp;
    static Outdoors* onlyInstance;
    Outdoors() {}

    static void makeAnimal()
    { temp = new Animal(); }
    };
    Outdoors* Outdoors::onlyI nstance = 0;
    //end outdoors.h
    *************

    animal.h
    **********
    class Animal
    {
    public:
    Animal() {}
    private:
    };

    Many thanks!
    //Tony


  • Rade

    #2
    Re: unresolved references when using static

    You should have defined Outdoors::temp just the same way you have defined
    Outdoors::onlyI nstance:

    Animal *Outdoors::temp = 0;

    Think of moving the definitions to a cpp file (see my previous post).

    Rade


    Comment

    Working...