如何在C++的多个类中组织包含

How to organize includes includes in multiple Classes in C++

本文关键字:包含 C++      更新时间:2023-10-16

首先,我是编程的初学者,所以不要指望我能理解每个特定于代码的单词。

其次,我有时吸收速度很慢。

第三,我想我涵盖了C++的基础知识,但仅此而已。当然,我很高兴能学到更多!

对于我的问题:

我正在编写一些代码来体验类。我创建了两个类,每个类在不同的 .h 和 .cpp 文件中。现在每个人都使用标题iostreamstring

我应该如何在不产生任何问题的情况下包括这些?#pragma一次就足够了吗?

第二个问题是关于using namespace std: 我应该把它放在哪里(我知道这不是一个糟糕的用途,但仅适用于一个小程序(

第一个标题:

#pragma once
#include <iostream>
#include <string>  
//using namespace std Nr.1
class one
{
};

第二个标题:

#pragma once
#include <iostream>
#include <string>  
//using namespace std Nr.2
class two
{
};

最后主要:

#include "one.h"
#include "two.h"
//using namespace std Nr.3
int main()
{
return 1;
};

提前感谢您的回复。

在两个类标头中包含两次 iostream 和字符串都没有问题。

#pragma 指令用于保护您自己的类型的两个类型(typedef、类(声明。

因此,它适用于您的类标头。

此外,使用 #pragma 指令也有缺点 https://stackoverflow.com/a/1946730/8438363,如下所述:

我建议使用预处理器定义保护:

#ifndef __MY_HEADER__
#define __MY_HEADER__

//... your code here
#endif

希望这有帮助。

您需要使用包含防护。它们确保编译器只包含每个"包含"头文件(#include"XXX.h"(一次。

但是,如果您正在创建一个小型应用程序并且不介意在需要时重新编译/重建整个项目,那么将公共头文件放在专用头文件中是公平的游戏并保持代码干净和小。

您还可以创建一个包含所需所有常见依赖项的标头,并将其包含在需要这些依赖项的每个类中。下面是一个简单的示例:

核心.h

#include <iostream>
#include <string>
// include most common headers
using namespace std;

一.h

#pragma once
#include "Core.h"
// if you need a header only for this class, put it here
// if you need a header in mutiple classes, put in Core.h
namespace one {
class One
{
public:
One();
~One();
void sumFromFirstNamespace(string firsNumber, string secondNumber)
{
//convert string to int
int first = stoi(firsNumber);
int second = stoi(secondNumber);
int result = first + second;
cout << result << endl;
}
};
}

二.h

#pragma once
#include "Core.h"
// if you need a header only for this class, put it here
// if you need a header in mutiple classes, put in Core.h
namespace two{
class Two
{
public:
Two();
~Two();
void sumFromSecondtNamespace(string firsNumber, string secondNumber)
{
//convert string to int
int first = stoi(firsNumber);
int second = stoi(secondNumber);
int result = first + second;
cout << result << endl;
}
};
}

主.cpp

#include "One.h"
#include "Two.h"
int main()
{
one::One firstClass;
two::Two secondClass;
firstClass.sumFromFirstNamespace("10", "20");
secondClass.sumFromSecondtNamespace("20", "30");
}

在某些情况下,您需要在两个不同的类中使用相同的 10+ 标头,我认为将它们放在一个标头中可以帮助您更好地查看代码。 是的,预处理器定义也很好,不要忘记这一点。(: