类的转发声明似乎不工作在C ++ [英] Forward declaration of class doesn't seem to work in C++

查看:181
本文介绍了类的转发声明似乎不工作在C ++的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

下面的代码在VC ++ 6中编译。我不明白为什么我得到编译错误 C2079:'b'使用未定义的类'B'为以下代码。

The follwing code is compiled in VC++6. I don't understand why I am getting the compilation error C2079: 'b' uses undefined class 'B' for the following code.

B类来源

#include "B.h"

void B::SomeFunction()
{
}

strong> B类标题

Class B Header

#include "A.h"

struct A;

class B
{
    public:
        A a;
        void SomeFunction();
};

struct A标题

#include "B.h"

class B;

struct A
{
    B b;
};

如果我将B类标题更改为以下内容,那么将没有错误。但是头声明不会在顶部!

If I changed class B header to the following, then there will be no error. But the header declaration won't be at the top!

具有古怪头声明的B类头

struct A;

class B
{
     public:
        A a;
        void SomeFunction();
};

#include "A.h"


推荐答案

为了定义类或结构,编译器必须知道类的每个成员变量有多大。前向声明不这样做。我只看过它用于指针和(不太经常)引用。

In order to define a class or struct, the compiler has to know how big each member variable of the class is. A forward declaration does not do this. I've only ever seen it used for pointers and (less often) references.

除此之外,你想在这里做的不能做。您不能拥有包含类别A的对象的另一个类别B的对象的类A。您可以 A包含指向类B的指针,其中包含类A的对象

Beyond that, what you're trying to do here cannot be done. You cannot have a class A that contains an object of another class B that contains an object of class A. You can, however, have class A contain a pointer to class B that contains an object of class A.

B.cpp

#include "B.h"

void B::SomeFunction()
{
}

Bh​​ b
$ b

B.h

#ifndef __B_h__  // idempotence - keep header from being included multiple times
#define __B_h__
#include "A.h"

class B
{
public:
    A a;
    void SomeFunction();
};

#endif // __B_h__

#ifndef __A_h__  // idempotence - keep header from being included multiple times
#define __A_h__
#include "B.h"

class B; // forward declaration

struct A
{
    B *b;  // use a pointer here, not an object
};

#endif // __A_h__

两点。首先,确保使用某种形式的幂等性,以防止头文件被每个编译单元多次包含。第二,了解在C ++中,类和结构之间的唯一区别是默认的可见性级别 - 类默认使用私有可见性,而结构体默认使用公共可见性。以下定义在C ++中的功能等价。

Two points. First, be sure to use some form of idempotence to keep the headers from being included multiple times per compilation unit. Second, understand that in C++, the only difference between classes and structs is the default visibility level - classes use private visibility by default while structs use public visibility by default. The following definitions are functionally equivalent in C++.

class MyClass
{
public: // classes use private visibility by default
    int i;
    MyClass() : i(13) { }
};

struct MyStruct
{
    int i;
    MyStruct() : i(13) { }
};

这篇关于类的转发声明似乎不工作在C ++的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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