简体   繁体   中英

C++ Simple circular reference and forward declaration issue

I get this error:

error C3646: 'bar': unknown override specifier

when trying to compile this very simple C++ code in Visual Studio 2015:

main.cpp :

#include "Foo.h"

int main ()
{
    return 0;
}

Foo.h :

#pragma once

#include "Bar.h"

class Foo
{
public:
    Foo();

    Bar bar;
};

Bar.h :

#pragma once

#include "Foo.h"

class Bar
{
public:
    Bar();
};

I get there is a circular reference because each .h includes the other, and the solution should be using forward declarations , but they don't seem to work, could someone explain why? I found similar problems here, and the solutions is always the same, I think I'm missing something :)

The circular reference is entirely of your own making, and you can safely remove it by removing the #include "Foo.h" from Bar.h:

#pragma once

//#include "Foo.h"  <---- not necessary, Bar does not depend on Foo

class Bar
{
public:
    Bar();
};

You do not need a forward declaration of Bar inside Foo.h . A more general case would be if Foo and Bar were mutually dependent on each other, that would require forward declarations.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM