C ++:命名空间-如何在头文件和源文件中正确使用? [英] C++: Namespaces -- How to use in header and source files correctly?

查看:728
本文介绍了C ++:命名空间-如何在头文件和源文件中正确使用?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

考虑一对两个源文件:接口声明文件(*.h*.hpp)及其实现文件(*.cpp).

Consider a pair of two source files: an interface declaration file (*.h or *.hpp) and its implementation file (*.cpp).

*.h文件如下所示:

namespace MyNamespace {
  class MyClass {
  public:
    int foo();
  };
}

我已经看到在源文件中使用名称空间的两种不同做法:

I have seen two different practices for using namespaces in source files:

*.cpp显示练习1:

#include "MyClass.h"
using namespace MyNamespace;

int MyClass::foo() { ... }

*.cpp显示练习2:

#include "MyClass.h"
namespace MyNamespace {

  int MyClass::foo() { ... }

}

我的问题:这两种做法之间是否有任何区别,一种被认为比另一种更好?

My question: Are there any differences between these two practices and is one considered better than the other?

推荐答案

从代码可读性的角度来看,出于这个原因,使用#2方法可能更好:

From a code readability standpoint, it is probably better in my opinion to use the #2 method for this reason:

您一次可以是多个名称空间,并且在该行下编写的任何对象或函数都可以属于这些名称空间中的任何一个(除非命名冲突).将整个文件包装在namespace块中更为明确,并且允许您在.cpp文件中声明属于该名称空间的新函数和变量.

You can be using multiple namespaces at a time, and any object or function written below that line can belong to any of those namespaces (barring naming conflicts). Wrapping the whole file in a namespace block is more explicit, and allows you to declare new functions and variables that belong to that namespace within the .cpp file as well

这篇关于C ++:命名空间-如何在头文件和源文件中正确使用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆