我正在学习C++,我正在尝试创建一个“在线商店”,在那里你可以发布文章并对它们进行评论,一条评论属于一篇文章,一篇文章可以有很多评论,但我现在不知道如何在不创建循环的情况下对其进行编码
我尝试过使用Article.hComment.h# -> "Comment.h“,反之亦然,但是当我试图编译它时,它创建了一个循环,其中A导入B,B导入A
Comment.h
#include <string>
//This is what I've tried but it creates a loop
#include "Article.h"
using namespace std;
//Class
class Comment
{
private:
Article article;
string description;
string rating;
};
Article.h
#include <string>
#include <map>
//The other part of my buggy-loop
#include "Comentario.h"
class Article
{
private:
map<string, int> art_comments;
string name;
string rating;
};
更新
谢谢大家,你给我的Resolve build errors due to circular dependency amongst classes解决了我的问题
因为这个问题已经解决得比较早了,我应该删除这篇文章吗?
发布于 2019-06-13 03:43:30
这是一个很好的问题!使用对文章的引用和转发声明可能是你想要做的,尽管我看不出有太多的理由让评论知道关于文章的任何事情,特别是因为文章可能会使用std::vector< Comment>拥有它的所有评论。
现在,您的comentario.h文件如下所示:
// comentario.h
class Comment {
public:
...
private:
Article article;
[other implementation details for an Article]
}
既然你的评论绝对不应该拥有一篇文章,我们可以这样重写comentario.h:
// comentario.h
class Article; // this is a forward declaration in order to reference an Article
class Comment {
public:
Comment(Article& article) // a Comment constructor--requires an Article
... // other Comment implementation details
private:
Article& article; // reference an existing Article
...
// no need for Article implementation details at all in Comment
}
// comentario.cpp
#include "include/comentario.h"
#include "include/article.h" // we can include article.h now since we're outside the header
Comment::Comment(Article& article) // the Comment constructor
: article(article) { // initialize the reference to an Article
}
这是实现这一点的一种方法。我个人不会对文章进行任何评论,但如果有必要,我会为文章细节创建一个只读包装,比如标题,然后在评论中引用它。
附注:许多程序员不鼓励在头部中使用命名空间xx。
https://stackoverflow.com/questions/56565958
复制相似问题