关于c++头文件中类声明的问题

about class declaration in header file C++

本文关键字:声明 问题 c++ 文件 关于      更新时间:2023-10-16

问题在这里。我需要用两个类来写头文件,比如A类和b类。

在A类中,我有一个使用B类对象的函数,反之亦然,即在B类中,我有一个使用A类对象的函数。

如果A先声明,则会错误地认为没有声明类B。如何处理?我尝试在类B声明后声明类a的函数:

void classA::myfunc (classB *b);

但是我得到了函数myfunc没有声明的错误。有c++经验的人,该怎么办?

补充道:这是一个关于header

的链接

如果你需要一个指针指向一个类的头,而不是整个对象,只需添加一个前向声明,不包括指针类的头。

我肯定你只是使用指针访问类,一个有引用到另一个,不是吗?因为如果你使用实例,你会得到一个实例循环。使用前向声明

下面是一个如何使用前向声明的例子:

A.h

class B;
class C;
class D;
class E;
class A {
    B* pointer; //To just have a pointer to another object.
    void doThings(C* object); //if you just want to tell that a pointer of a object is a param
    D* getThings(); //if you wanna tell that a pointer of such class is a return.
    E invalid(); //This will cause an error, because you cant use forward declarations for full objects, only pointers. For this, you have to use #include "E.h".
};

为了说明如何有一个类提到一个指向其类型的类:

B.h

class A;
class B {
    A* pointer; //That can be done! But if you use a includes instead of the forward declarations, you'll have a include looping, since A includes B, and B includes A.
}

正如Tony Delroy所提到的(非常感谢他),你不应该总是使用这种设计。它是由c++编译器提供的,但这不是一个好的做法。最好是提供引用头,这样您的代码看起来像:

A.h

#include "B.fwd.h"
#include "C.fwd.h"
#include "D.fwd.h"
#include "E.fwd.h"
class A {
    B* pointer; //To just have a pointer to another object.
    void doThings(C* object); //if you just want to tell that a pointer of a object is a param
    D* getThings(); //if you wanna tell that a pointer of such class is a return.
    E invalid(); //This will cause an error, because you cant use forward declarations for full objects, only pointers. For this, you have to use #include "E.h".
};

和你的转发头,像这样:

B.fwd.h:

class B;

在你的文件中,你应该有你的类前向声明,以及它带来的任何类型定义。

我没有提到#pragma once,或者#ifndef B.H...你知道它们会在那里:D

您的代码将在<iosfwd>定义的标准上,并且更好地维护,特别是如果它们是模板。

简短回答:

class classA;

然后定义了类b,然后声明了类a。

这被称为前向声明,是用来解决你的问题的:)

您可以尝试在与ref或ptr一起使用类之前添加类的前向声明。

classA.h:

class classB;
class classA {
    void fun(classB * b);
}

classB.h:

class classA;
class classB {
    void fun(classA * a);
}

classA.cpp:

#include "classA.h"
#include "classB.h"
...

classB.cpp:

#include "classA.h"
#include "classB.h"
...