C++中的"typedef"、"using"、"namespace"和"using namespace"有什么区别?

What are the differences between "typedef", "using", "namespace" and "using namespace" in C++?

我发现很难在 C++ 中获得这些术语的确切含义。似乎彼此之间有很多重叠(至少 typedef 和命名空间)。你能告诉我为什么这些概念是用 C++ 发明的吗?在什么情况下我们应该使用其中的每一个?

另外this讨论特别混乱。它说 'typedef' 和 'using' 是一样的。这让我想知道,如果它们几乎相同,为什么我们有两个不同的术语?

由于对这些术语的理解不足,我编写了以下代码并得到如下所示的错误:

Files.hpp

#include <boost/filesystem.hpp>
#include <boost/filesystem/path.hpp>
#include <boost/filesystem/operations.hpp>
#include <iostream>
#include <vector>
#include <string>
#include <utility>
#include <algorithm>
#include <fstream>
#include <ostream>
#include <iomanip>
#include <cmath>

class Files {

public:

//@Brief: We create some short forms for long type names
typedef boost::filesystem FS; //! Short form for boost filesystem
// Short form for file name pairs (for example, <200.jpg, 200>)
typedef std::pair<FS::path, int> file_entry;
// Short form for vector of tuples
typedef std::vector<file_entry> vec;
// Short form for iterator of type, boost::filesystem::directory_iterator
typedef FS::directory_iterator dirIter;
};

以下是我收到的 make 错误:

...../include/Files.hpp:10:20: error: ‘filesystem’ in namespace ‘boost’ does not name a type
 typedef boost::filesystem FS; //! Short form for boost filesystem

boost::filesystem 是命名空间,不是类型。所以你可以这样做:

namespace FS = boost::filesystem;

因为 boost::filesystem 不是类型而是 namespace。在文件范围内使用名称空间别名:

namespace FS = boost::filesystem;