使用C ++头文件的最佳做法 [英] Best practices for use of C++ header files
问题描述
我对头文件使用有以下疑问。
I have the following doubts on header files usage.
1 - 包括置于注释之后的警卫
/* Copyright Note and licence information (multiple lines) */
#ifndef FOO_H
#define FOO_H
// Header file contents
#endif
Herb Sutter在他的C ++编码标准像上面的问题。他说的是#ifndef语句应该出现在头文件的第一行。我没有觉得这是令人信服的。
Herb Sutter says in his "C++ coding standards" book that code like the above is problematic. He is saying the "#ifndef" statements should appear in the first line of the header file. I haven't felt this as convincing. Is this followed by you guys/gals in header files?
2 - 在头文件中使用命名空间
#ifndef FOO_H
#define FOO_H
namespace FooNameSpace{
// Header file contents
}
#endif
上述代码是否使用正确的做法?我的意思是,你在头文件中使用命名空间吗?我知道为什么在头文件中导入命名空间是无意义的,但是如上所述的声明呢?
Is the above code using correct practice? I mean, do you use namespaces in header files? I know why importing a namespace in header file is pointless but what about a declaration like the above?
如果上面的一个是正确的方法, em>向前声明在另一个命名空间中的类?就像
If the above one is the correct method, how do you do "forward declaration" of a class which is in another namespace? Is it like
#ifndef FOO_H
#define FOO_H
namespace AnotherNameSpace{
class AnotherFoo; // forward declaration
}
namespace FooNameSpace{
// Use AnotherFoo here
}
#endif
向前声明是避免循环依赖 ?
推荐答案
-
包含守卫和注释的顺序完全是一个问题
The order of the include guards and the comments is purely a matter of style - it won't have any measurable effect on speed of compilation.
命名空间绝对应该在头文件中用于声明函数,类,全局变量等。 。你应该不是 c>使用在头文件中使用
语句 - 不可能在包含它的源文件中取消使用某些东西,不应该强迫包含器向全局范围添加额外的东西。如果你需要使用头部中其他命名空间的东西,完全限定每个名字。
Namespaces absolutely should be used in header files for declaring functions, classes, globals, etc. What you should not do is use using
statements in header files -- it's impossible to unuse something in a source file that includes it, and you shouldn't force includers to add extra stuff to the global scope. If you need to use things from other namespaces in your headers, fully qualify every name. It can be a pain sometimes, but it's really the right thing to do.
示例:
// WRONG!
using namespace std;
class MyClass
{
string stringVar;
};
// RIGHT
class MyClass
{
std::string stringVar;
};
对于其他命名空间中的类的前向声明,只要记住在你的标题中引用 AnotherFoo
作为 AnotherNameSpace :: AnotherFoo
事实上,前向声明是打破循环依赖的唯一方法。
As for forward declarations of classes in other namespaces, you've got it exactly right. Just remember to always qualify AnotherFoo
as AnotherNameSpace::AnotherFoo
when you reference it inside your header. Indeed, forward declarations are the only way to break cyclic dependencies.
这篇关于使用C ++头文件的最佳做法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!