简体   繁体   English

c ++在另一个类头文件中声明一个类

[英]c++ declaring a class in another class header file

#ifndef PC
#define PC
#include <iostream>
#include <string>
#include "../include/worm.h"
#include "../include/dns.h"

class DNS; // Forward decleration

class PC
{
....(there is all the declration here)  
};

#endif

why is there the "class DNS;"? 为什么会有“类DNS”? what is the purpose of writing that?(if you need more of the code to understand the need\\purpose let me know) 写这个的目的是什么?(如果你需要更多代码来了解需要\\目的让我知道)

We would need more code, specifically DNS's header file, but I'm assuming dns.h also includes pc.h. 我们需要更多的代码,特别是DNS的头文件,但我假设dns.h还包括pc.h. When you have two header files that include each other, they must each forward declare the other class. 如果有两个相互包含的头文件,则每个头文件都必须向前声明另一个类。

However, if dns.h does not include pc.h, then you don't need the forward declaration. 但是,如果dns.h不包含pc.h,那么您不需要前向声明。

My understanding of it involves circular dependencies. 我对它的理解涉及循环依赖。 Imagine I'm walking through dns.h, and I see pc.h. 想象一下,我正在浏览dns.h,我看到了pc.h. I need to know what you depend on, so now I start going through pc.h. 我需要知道你所依赖的东西,所以现在我开始通过pc.h. I now see dns.h, but I was just there so I keep going through pc.h. 我现在看到dns.h,但我就在那里,所以我继续通过pc.h. If you use DNS inside of class PC, how am I to know what DNS is? 如果你在类PC中使用DNS,我怎么知道DNS是什么? I stopped walking through dns.h before I hit that class declaration. 在我点击那个类声明之前,我停止了通过dns.h。

The solution is to foreward declare the class in pc.h. 解决方案是在pc.h中声明该类。 This gives me just enough information to know that DNS is a class of some sort, and to not freak out when I see arguments, variables, etc. of type DNS. 这给了我足够的信息,知道DNS是某种类的类,并且当我看到DNS类型的参数,变量等时不要惊慌失措。 I now have confidence DNS will be defined later. 我现在有信心DNS将在稍后定义。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM