Pregunta

I've written the following code:

//--a.cpp--//
#include "base.h"


class B : public A
{
public:
    void foo()
    {
        A::bar();
    }
};

int _tmain(int argc, _TCHAR* argv[])
{
    B *b= new B();
    b->foo();
    return 0;
}

//--b.cpp--//
#include "base.h"

void A::bar()
{
        printf("class A");
}


//--base.h--//

class A
{
public:
    void bar();
};

And it works. But I don't understand why it works correctly, but it doesn't work when we're put the class A definition into the a.cpp and b.cpp instead of base.h. I think that after preprocessing phase and before the compiling to object module the base.h just replaced to the content of base.h. And we have still redefinition of class A before the compilation phase.

¿Fue útil?

Solución

Both a.cpp and b.cpp need access to the declaration of class A (which is what you have in base.h). I copied and pasted the contents of base.h (the declaration) at the top of a.cpp and b.cpp, and it compiled fine in Visual Studio 2012.

You do not want to put the definition of class A in both files. Classes can be declared in multiple places, but must be defined in only one.

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top