【问题标题】:Visual C++ (C++/CLI) Forward Declaration with Derivative Classes?带有派生类的 Visual C++ (C++/CLI) 前向声明?
【发布时间】:2012-06-06 23:11:26
【问题描述】:

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

啊.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"

#ifdef/#pragma 守卫应该保持 *.h 不被读取两次,并强制 b.h 首先被读取,并且从编译器输出中我很确定它们是。 (我什至不确定#pragma once 和#include 放置是否需要#ifdef/#define)

但是,编译器抱怨 path/a.h: error C2011: 'class' type redefinition。 见文件路径/B.h

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

【问题讨论】:

    标签: visual-c++ c++-cli forward-declaration


    【解决方案1】:

    需要进行两项更改:

    1. 在类定义的右大括号后添加分号。
    2. 在 A.h 中,将 #pragma once 移动到文件的第一行。把它放在#ifdef 块内会搞砸。

    另外,请注意,更简单的方法是不让任何一个头文件包含另一个,并在两个文件中使用前向声明:

    啊哈:

    #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;
    };
    

    【讨论】:

    • 通过在#ifdef 之外移动#pragma 一次,如果首先预处理A.h,则未定义A。此外,我需要使用 .cpp 文件中引用的方法,因此我需要在 .h 文件中的某处使用 #include,但使用第二种方法并在 .h 的作品底部添加 #include !谢谢!
    • 要解决这个问题,我建议您从头文件底部删除该#include,并从您的.cpp 文件中简单地#include A.h 和B.h。
    • 在 .cpp 文件中放入#include 不是不好的做法吗? (并不是说所有东西在预处理后都没有全部混合在一起)
    • 我不知道。如果你的项目使用预处理的头文件,通常将项目外部的#includes放入stdafx.h(例如#include<windows.h>),但对于项目内部的头文件,通常有六个#includes每个 .cpp 文件或更多文件的顶部。
    猜你喜欢
    • 2020-06-04
    • 2011-11-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-05-28
    • 2021-12-25
    • 1970-01-01
    相关资源
    最近更新 更多