문제

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.

도움이 되었습니까?

해결책

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.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top