头文件包含和依赖项的顺序

Order of header file inclusions and dependencies

我只是想测试将代码拆分成多个文件。

我有:

//testMultiple.cpp

#include <string>
#include <iostream>
#include "testInclude.cpp"

int main(){
    std::cout << "hi";
}

//testInclude.cpp

class testClass{
    public:
        string x;
};

这给了 testInclude.cpp:3:9: error: ‘string’ does not name a type

我想既然它在包含 testInclude.cpp 之前就包含了,那么字符串将被定义为在 testInclude.cpp 中使用。

您需要使用 std::string 而不是 string

使用

class testClass{
    public:
        std::string x;
};

您包含的是 cpp 文件,而不是 hpp 文件。 通常的做法是包含头 (h/hpp) 文件,而不是实现 (c/cpp) 文件。

如果只编译 testMultiple.cpp,这应该可以。如果编译器单独编译 testInclude.cpp,它不会看到`#include

尝试将 testInclude.cpp 重命名为 testInclude.hpp 并确保它没有被编译。

这是一个例子:

///// testInclude.h
#include <vector>
class testClass{
    public:
         std::vector<int> x; // vector is in std namespace
};

///// testMultiple.cpp
// #include <vector> - gets this through testInclude.h
#include "testInclude.h"

int main(){
}