This is the context:

I have a class A which should say 'Hi", but since A does not knows to speech, it uses an object of class B to speech for him. Since the only purpose of A holding an B is to B speech for it, there's no need of each A hold it's own B object; because of this I choose to use an unique static private B for this.

Like this:

class A {
    static B b;
public:
    void sayHi();
};

void A::sayHi()
{
    b.sayHi();
}

And B goes like this:

class B {
public:
    void sayHi();
};

void B::sayHi() 
{
    std::cout << "Hi!" << std::endl;
}

The problem is when I try to compile this code with g++ compiler...

int main() {
    A a;
    a.sayHi();
    return 0;
}

I get an "undefined reference" error. I'm not sure why this is not working, I was wondering that the compiler thinks I'm referring to an non-static B in A, but I don't know how it should be.

P.S.: In my code, the declaration of B comes before declaration of A.

有帮助吗?

解决方案

You need to actually create the static object somewhere in your code. All you've done is say the class has one. Add this to a .cpp file:

B A::b;

This assumes the object should be default constructed.

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top