简体   繁体   English

如何组织类以共享数据成员但保留封装c ++?

[英]How to organize classes to share data members but preserve encapsulation c++?

I want to build a tree breadth first in c++ using a queue. 我想首先使用队列在C ++中建立树宽。 I have the files Queue.h, Queue.cpp, Tree.h, Tree.cpp, and main.cpp. 我有文件Queue.h,Queue.cpp,Tree.h,Tree.cpp和main.cpp。 My main class #includes "Tree.cpp". 我的主要课程包括“ Tree.cpp”。 How do I structure these files using the #include keyword so that my Queue can push and pop tree nodes, and my tree can manipulate the Queue? 如何使用#include关键字构造这些文件,以便我的队列可以推送和弹出树节点,而我的树可以操纵队列? It seems that part of the problem I am having is that the struct in each class is private. 看来我遇到的部分问题是每个类中的结构都是私有的。 My Queue cannot define a treePtr in its struct, and my tree cannot instantiate new queue nodes. 我的队列无法在其结构中定义treePtr,并且我的树无法实例化新的队列节点。 Should I make the structs in each class public so they can access each other across classes? 我是否应该在每个班级中公开这些结构,以便它们可以跨班级相互访问? In general, how am I suppose to organize these classes to make use of encapsulation? 通常,我应该如何组织这些类以利用封装?

class Tree{
private:
    typedef struct tree {
        int data;
        tree* left;
        tree* right;
    }* treePtr;

    treePtr root;
    int numNodes;
    void addTree(int n, treePtr child);
    treePtr addTree(int n);


public:

    Tree();
    void addTreeNode(int integer);
    treePtr getRoot();
    void printTreeNode(int n, treePtr treeRoot);

};


class Queue {
private:
    typedef struct node {
        Tree::treePtr treeNode;
        node* next;
    }* nodePtr;

    nodePtr head;
    nodePtr current;

public:
    Queue();
    void push(treePtr t);
    int pop();
};

Per @Eugene, the answer is to make Tree and Queue mutual friends. 对于@Eugene,答案是让Tree和Queue成为共同的朋友。 This is done in the header files for each class inside the class body. 这是在类主体内每个类的头文件中完成的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM