gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 03:20:04 24 4
gpt4 key购买 nike

我有 2 个文件 Article13Filter.hArticle.cpp我在其中定义了位于 .h 中的类的所有已声明函数文件。然而,他的 VS 编译器告诉我在 Article13Filter.h归档 Article13Filter我在每个函数的定义之前写的词(表示它属于那个类)不是类或命名空间名称,即使是 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"。通常,您希望编译和链接 .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 文件中,特别是在类定义之前,类方法的声明在定义类之前被编译器看到。

关于c++ - 在头文件中编写的类的成员函数的定义,在 C++ 中单独的 .cpp 文件中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53137863/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com