简体   繁体   English

如何在课堂上访问私有结构?

[英]How to access private struct in class?

I want to access my Node struct in order to create a function that generates a new node. 我想访问我的Node结构,以创建一个生成新节点的函数。 To do so i thought that the only way to do it is to create a constructor inside my struct and to call the constructor in my CreateNode function. 为此,我认为唯一的方法是在我的结构中创建一个构造函数并在我的CreateNode函数中调用该构造函数。 However i get an error :[Error] 'struct BS::Node' is protected. 但是我得到一个错误:[Error]'struct BS :: Node'受保护。 An ovious sollution to the problem is to make struct Node public however i want to ask if there is another way to access my struct and keep it private. 一个解决该问题的方法是将struct Node公开,但是我想问一问是否还有另一种访问我的struct并将它保持私有的方法。

Header file 头文件

class BS
{
public:
    BS();     //constructor
protected:
    struct Node{
        int data;
        Node* left;
        Node* right;
        Node(int d,Node* lf ,Node* ri)
            :data(d),left(lf),right(ri){}
    }; 
    Node* root;    
    Node* CreateNode(int data);
};

CPP CPP

BS::BS(){
  root=NULL;
}  
BS::Node* CreateNode(int data){
    Node* new_node= new Node(0,NULL,NULL);
    return new_node;
}

Use a public class with a private constructor, and make the outer class a friend: 将公共类与私有构造函数一起使用,并使外部类成为朋友:

class BS
{
public:
  BS();     //constructor

  class Node {
    // note: private constructor
    Node(int d,Node* lf ,Node* ri)
    :data(d),left(lf),right(ri){}

    int data;
    Node* left;
    Node* right;

    // befriends BS
    friend BS;
  }; 

  Node* CreateNode(int data);

private:
  Node* root = nullptr;
};

BS::Node* BS::CreateNode(int data){
    Node* new_node= new Node(0, nullptr, nullptr);
    return new_node;
}

int main()
{

}

ps. ps。 don't use raw pointers. 不要使用原始指针。 Use std::unique_ptr 使用std::unique_ptr

No, you can not create your CreateNode function the way you would like, even with friendship, because this function returns a BS::Node outside BS , while Node is protected: 不,你不能创建CreateNode功能,你会喜欢的方式,甚至是友谊,因为这个函数会返回一个BS::Node之外的BS ,而Node保护:

#include <BS.hh>

BS::BS()
{
  root=nullptr;
}

BS::Node* BS::CreateNode(int data)
{
    BS::Node* new_node = new BS::Node(0,nullptr,nullptr);
    return new_node;
}

int main()
{
  BS bs;
  BS::Node* = bs.CreateNode(1); // <- Error, returning a BS::Node outside BS!
  return 0;
}

But you could use CreateNode inside BS with: 但是您可以在BS内部使用CreateNode与:

class BS
{
public:
    BS();     //constructor
protected:
    struct Node{
        int data;
        Node* left;
        Node* right;
        Node(int d,Node* lf ,Node* ri)
            :data(d),left(lf),right(ri){}
    };
    BS::Node* CreateNode(int data);
    BS::Node* root = CreateNode(0); // inside BS it's OK
};

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

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