关于c++头文件中类声明的问题
about class declaration in header file C++
问题在这里。我需要用两个类来写头文件,比如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"
...
相关文章:
- Visual Studio中的函数声明和函数定义问题
- 如何在标头中声明(或定义)函数的问题
- 在顶点着色器中使用 OpenGl 的未声明标识符,我在顶点着色器中绘制三角形时遇到问题
- 如何解决这个正向类声明问题
- NetBeans IDE 8.2 C++字符串声明问题
- C++通告声明问题
- 外部变量和数组声明问题C
- 错误C2447,应为声明问题
- 面向C++的main.cpp中的可视化结构声明问题
- C++/CLI转发声明问题
- C++中跨源文件的函数声明问题
- 这个简单(?C++字符串声明问题似乎已经击败了StackExchange
- 前向声明问题:嵌套名称说明符中使用的类型不完整'enums::Category'
- c++数组/指针声明问题
- 编译时Time_t声明问题
- 类声明问题
- 命名空间和前向声明问题
- 成员类声明问题
- QT c++前向声明问题
- C++数组声明问题