如何在C++的多个类中组织包含
How to organize includes includes in multiple Classes in C++
首先,我是编程的初学者,所以不要指望我能理解每个特定于代码的单词。
其次,我有时吸收速度很慢。
第三,我想我涵盖了C++的基础知识,但仅此而已。当然,我很高兴能学到更多!
对于我的问题:
我正在编写一些代码来体验类。我创建了两个类,每个类在不同的 .h 和 .cpp 文件中。现在每个人都使用标题iostream
和string
。
我应该如何在不产生任何问题的情况下包括这些?#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+ 标头,我认为将它们放在一个标头中可以帮助您更好地查看代码。 是的,预处理器定义也很好,不要忘记这一点。(:
- 如何导出包含具有"std::unique_ptr"值的"std::map"属性的
- 从包含m行的文件中提取n行,必要时(惰性地)重复该文件
- 编译包含字符串的代码时遇到问题
- c++库的公共头文件中应该包含什么
- 将包含C样式数组的对象初始化为成员变量(C++)
- 是否需要删除包含对象的"pair"?
- 函数何时会在c++中包含stack_Unwind_Resume调用
- 如何将包含epoch时间的十六进制字符串转换为time_t
- 使用mongocxx驱动程序时包含头文件问题
- 如何在h文件中包含.o对象文件
- 在混合代码库中将C转换为C++时出现许多包含错误
- VS2017,C++包含目录与附加包含目录,子文件夹包含失败-但为什么
- cmath抛出错误C2062、C2059、C2143和C2447.cmath包含在矢量文件中
- 为什么您需要C++头文件的包含保护
- 无法在UE4中包含BP类到CPP类
- g++ 说函数不存在,即使包含正确的标头
- 在C++代码中包含opencv时,使用ctypes创建.so文件
- Visual C++GC接口如何启用它以及要包含哪个库
- 当调用switch语句中的函数时(即使函数不包含循环),似乎是永不结束的循环的问题
- 为什么包含windows.h会产生语法错误,从而阻止类的实例化?(C2146,C2065)