首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >如何将A实现为B,将B实现为A(而不创建循环)?

如何将A实现为B,将B实现为A(而不创建循环)?
EN

Stack Overflow用户
提问于 2019-06-12 23:42:40
回答 1查看 130关注 0票数 1

我正在学习C++,我正在尝试创建一个“在线商店”,在那里你可以发布文章并对它们进行评论,一条评论属于一篇文章,一篇文章可以有很多评论,但我现在不知道如何在不创建循环的情况下对其进行编码

我尝试过使用Article.hComment.h# -> "Comment.h“,反之亦然,但是当我试图编译它时,它创建了一个循环,其中A导入B,B导入A

Comment.h

代码语言:javascript
复制
#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

代码语言:javascript
复制
#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解决了我的问题

因为这个问题已经解决得比较早了,我应该删除这篇文章吗?

EN

回答 1

Stack Overflow用户

发布于 2019-06-13 03:43:30

这是一个很好的问题!使用对文章的引用和转发声明可能是你想要做的,尽管我看不出有太多的理由让评论知道关于文章的任何事情,特别是因为文章可能会使用std::vector< Comment>拥有它的所有评论。

现在,您的comentario.h文件如下所示:

代码语言:javascript
复制
// comentario.h
class Comment {
public:
  ...
private:
  Article article;
  [other implementation details for an Article]
}

既然你的评论绝对不应该拥有一篇文章,我们可以这样重写comentario.h:

代码语言:javascript
复制
// 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。

票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/56565958

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档