Visual C++ (C++/CLI) Forward Declaration with Deri

2019-08-16 16:02发布

问题:

Okay, so I'm running into trouble with Forward Declarations in Visual Studios C++ (C++/CLI). The code is as follows:

A.h

#include "B.h"

#ifdef B_H
#pragma once

public ref class A : public base_class  //base_class is public, memory managed 
{
    B^ b;
}

#endif

B.h

#define B_H

#pragma once

ref class A;

ref class B 
{
    A^ a;
}

#include "A.h"

The #ifdef/#pragma guards should keep be keeping a *.h from being read twice, and forcing b.h to be read first, and from the compiler output I'm pretty sure they are. (I'm not even sure the #ifdef/#define is needed with the #pragma once and #include placement)

But, the complier complains of a path/a.h: error C2011: 'class' type redefinition. See file path/B.h

Should I be doing something with the forward declaration of A because it's a derivative class in the actual class definition, or am I barking up the wrong tree?

回答1:

Two changes needed:

  1. Add semicolons after the closing brace of the class definitions.
  2. In A.h, move the #pragma once to be the very first line in the file. It's getting screwed up by having this inside the #ifdef block.

Also, note that a simpler way to do this would be to not have either header file include the other, and use forward declarations in both files:

A.h:

#pragma once
ref class B;
public ref class A : public base_class  //base_class is public, memory managed 
{
    B^ b;
};

B.h

#pragma once
ref class A;
ref class B 
{
    A^ a;
};