class 的成员函数的定义写在头文件中,在 C++ 中单独的 .cpp 文件中

Definition of member functions of a class written in a header file, in a separate .cpp file in C++

我有 2 个文件 Article13Filter.hArticle.cpp,其中我定义了位于 .h 文件中的 class 的所有声明函数。但是,他的 VS 编译器告诉我,在 Article13Filter.h 文件中,我在每个函数定义之前写的 Article13Filter 词(表示它属于那个 class)不是 class 或命名空间名称,即使 include 指令已正确包含到其相应的文件中?请问这是为什么?

Article13Filter.h 文件:

#ifndef ARTICLE_13_FILTER_H
#define ARTICLE_13_FILTER_H
#include <string>
#include <vector>
#include <set>
#include "Article.cpp"
class Article13Filter {
private:
    std::set<std::string> copyrighted;
    std::vector<std::string> blocked;
public:
    Article13Filter(std::set<std::string> copyrighted);
    bool blockIfCopyrighted(std::string s);
    bool isCopyrighted(std::string s);
    std::vector<std::string> getBlocked();
};
#endif // !ARTICLE_13_FILTER_H

Article.cpp 文件:

#include <iostream>
#include <string>
#include <set>
#include "Article13Filter.h"
using namespace std;
bool Article13Filter::isCopyrighted(string s) {
    for (set<string>::iterator it = copyrighted.begin(); it != copyrighted.end(); it++) {
        if (*it == s) {
            return true;
        }
        return false;
    }
}
bool Article13Filter::blockIfCopyrighted(string s) {
    if (isCopyrighted(s)) {
        return false;
    }
    return true;
}
vector<string> Article13Filter::getBlocked() {
    return blocked;
}

从 Article13Filter.h 中删除 #include "Article.cpp"。通常,您希望编译和 link .cpp 文件并包含 .h 和 .hpp 文件。

当您包含一个文件时,它实际上是复制粘贴到包含文件中。 最终编译的文件看起来像

#include <iostream>
#include <string>
#include <set>

#include <string>
#include <vector>
#include <set>
#include <iostream>
#include <string>
#include <set>


using namespace std;
bool Article13Filter::isCopyrighted(string s) {
    for (set<string>::iterator it = copyrighted.begin(); it != copyrighted.end(); it++) {
        if (*it == s) {
            return true;
        }
        return false;
    }
}
bool Article13Filter::blockIfCopyrighted(string s) {
    if (isCopyrighted(s)) {
        return false;
    }
    return true;
}
vector<string> Article13Filter::getBlocked() {
    return blocked;
}

class Article13Filter {
private:
    std::set<std::string> copyrighted;
    std::vector<std::string> blocked;
public:
    Article13Filter(std::set<std::string> copyrighted);
    bool blockIfCopyrighted(std::string s);
    bool isCopyrighted(std::string s);
    std::vector<std::string> getBlocked();
};


using namespace std;
bool Article13Filter::isCopyrighted(string s) {
    for (set<string>::iterator it = copyrighted.begin(); it != copyrighted.end(); it++) {
        if (*it == s) {
            return true;
        }
        return false;
    }
}
bool Article13Filter::blockIfCopyrighted(string s) {
    if (isCopyrighted(s)) {
        return false;
    }
    return true;
}
vector<string> Article13Filter::getBlocked() {
    return blocked;
}

您收到的错误是因为通过将 cpp 文件包含在 .h 文件中,特别是在 class 定义之前,编译器之前看到了 class 方法的声明class 已定义。