Visual C ++(C ++ / CLI)具有派生类的前向声明? [英] Visual C++ (C++/CLI) Forward Declaration with Derivative Classes?

查看:261
本文介绍了Visual C ++(C ++ / CLI)具有派生类的前向声明?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

好的,所以我在Visual Studios C ++(C ++ / CLI)中的前向声明方面遇到了麻烦。
代码如下:

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

Ah

#include "B.h"

#ifdef B_H
#pragma once

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

#endif

Bh

#define B_H

#pragma once

ref class A;

ref class B 
{
    A^ a;
}

#include "A.h"

#ifdef /#pragma防护措施应避免* .h被读取两次,并强制bh首先被读取,并且从编译器输出中我可以肯定它们是被读取的。 (我什至不确定#pragma一次和#include放置是否需要#ifdef /#define)

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)

但是,编译器抱怨路径/错误:错误C2011:类类型重新定义。
请参阅文件路径/ Bh

我应该对A的前向声明做些什么,因为它是实际类定义中的派生类,还是我吠错了树?

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. 在类定义的大括号后添加分号。

  2. 在Ah中,将 #pragma一次移动成为文件中的第一行。将其包含在 #ifdef 块中会使其变得更糟。

  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:

Ah:

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

Bh

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

这篇关于Visual C ++(C ++ / CLI)具有派生类的前向声明?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆