如何从成员访问受保护的/私有的嵌套类指针 [英] How to access a protected/private nested class pointer from a member

查看:75
本文介绍了如何从成员访问受保护的/私有的嵌套类指针的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个如下的queue.h文件.

I have a queue.h file like the following.

是否可以从Main访问队列的头指针?

Is it possible that I can access the head pointer of the queue from Main?

如果是,我该怎么办?

If yes, what should I do in main?

由于头指针是一个类指针,并且它的类型是一个受保护的嵌套类,所以我认为我不能从main中访问它.

Since the head pointer is a class pointer, and its type is a protected nested class, I don't think I can access it from main.

因此,我尝试将函数getHead()创建为公共成员.但是,另一个问题来了,那就是我正在使用模板类.请指导我如何解决此问题.

Therefore, I try to create a function getHead() as public member. However, another problem comes, it is I am using template class. Please guide me how to solve this problem.

我的头文件:

#include <iostream>
#include <iomanip>
using namespace std;

class PCB
{
    public:
        int PID;
        string fileName;
};    

template<class T>
class myQueue
{
    protected:
        class Node
        {
            public:
                T info;
                Node *next;
                Node *prev;
        };

        Node *head;
        Node *tail;
        int count;

    public:
        void getHead(Node **tempHead);
};

template<class T>
void myQueue<T>::getHead(Node **tempHead)
{
    *tempHead = head;
}    
#endif 

我的主要是:

#include "myQueue.h"
#include <iostream>

int main()
{
    myQueue<PCB> queue;
    //How can I access the Head pointer of my Queue here?
    //queue.getHead(&tempHead);
    return 0;
}

推荐答案

要从类外部访问myQueue::Node,您需要稍微重写一下getter函数:

To acess myQueue::Node from outside the class you need to rewrite your getter function a bit:

template<class T>
myQueue<T>::Node* myQueue<T>::getHead()
{
    return head;
}

然后您可以像这样在main()中使用它

Then you can use it in main() like this

auto head = queue.getHead();

请注意,在这种情况下,auto的用法很重要.您仍然不能在myQueue<T>之外声明任何myQueue<T>::NodemyQueue<T>::Node**类型的变量,但是可以使用auto变量来保存这些类型.

Note that the usage of auto is important in this case. You still cannot declare any variable of type myQueue<T>::Node or myQueue<T>::Node** outside of myQueue<T>, but you can use auto variables to hold these types.

这篇关于如何从成员访问受保护的/私有的嵌套类指针的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆