头文件问题的无限循环 [英] infinite loop of headerfile problem
问题描述
大家好
我面临一个问题.
假设我有两个class.class A和class B.
在A类中,我定义了B类的对象,在B类中,我定义了A类的对象.
当我尝试运行代码时,它显示出在classA之前放置分号的错误.
代码是这样的.
#include"B_wnd.h"
类A_wnd {
int xy;
B_wnd b_obj;
};
在B类声明中,我正在这样使用
#include"A_wnd.h"
B_wnd类{
int bx;
A_wnd a_obj;
};
当我尝试查看代码时,出现错误.
谁能帮助我摆脱这个问题.
Hi All
I am facing a problem.
let suppose i have two classes.class A and class B.
in class A i defines the object of class B,and in class B i defines the object for class A.
When i try to run the code it show the error that to place a semicolon before the classA .
the code is something like this .
#include"B_wnd.h"
class A_wnd{
int xy;
B_wnd b_obj;
};
in class B declaration i am using like this
#include"A_wnd.h"
class B_wnd{
int bx;
A_wnd a_obj;
};
when i try to ru the code ,i get the error.
can any one help me in getting rid off from this problem.
推荐答案
那是一个循环引用,您不能这样做.重构代码.
That''s a circular reference, and you can''t do that. Refactor your code.
#include"B_wnd.h"
class A_wnd{
int xy;
B_wnd b_obj;
};
#include"A_wnd.h"
class B_wnd{
int bx;
A_wnd a_obj;
};
首先,为什么需要循环参考?任何真正的需求还是您只想测试?
首先,标题将具有循环引用.您可以使用包含保护程序来解决该问题.大多数情况下,所有高级C/C ++处理器都可以避免这种情况,但是始终在包含标头时使用包含防护.那么在Microsoft VCC中,我认为您可以使用
First of all why do you need a circular reference? Any real need or you want just to test?
First of all the headers will have circular reference. You can use a include guard to over come that. Mostly all advanced C/C++ processors can avoid it, but always when you include headers use include guards. In Microsoft VCC then I think you can use
#pragma once
克服这个问题后,您会遇到第二个问题.
假设您创建了一个A_wnd
类型的对象.
调用A_wnd
的构造函数时,它将调用B_wnd
的构造函数.在此内部,将再次调用A_wnd
的构造函数.这是一个递归问题.您将出栈并且会崩溃.
您可以使用指针或引用来代替实际对象.
After you overcome this you have a second problem.
Suppose you create an object of type A_wnd
.
When the constructor of A_wnd
is called it calls the constructors of B_wnd
. Inside this again constructor of A_wnd
will be called. This is a recursive problem. You will go out of stack and there will be crash.
You can use pointers or reference instead of real objects.
使用此:
//A_wnd.h
#ifndef A_H
#define A_H
#include "B_wnd.h"
class B_wnd;
class A_wnd
{
public:
B_wnd* m_b;
};
#endif
//B_wnd.h
#ifndef B_H
#define B_H
#include "A_wnd.h"
class A_wnd;
class B_wnd
{
public:
A_wnd* f;
};
#endif
2个重要问题:
1. ifndef-避免重新定义
2.转发定义(例如,类B_wnd).
2 important issues:
1. ifndef - to avoid redefinition
2. Forward definition (class B_wnd; for example).
这篇关于头文件问题的无限循环的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!