gpt4 book ai didi

c++ - 如何从成员访问 protected /私有(private)的嵌套类指针

转载 作者:行者123 更新时间:2023-11-30 03:31:27 25 4
gpt4 key购买 nike

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

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

如果是,在main中应该做什么?

由于头指针是一个类指针,而且它的类型是一个 protected 嵌套类,我想我不能从main访问它。

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

我的头文件:

#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 函数:

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

然后就可以在main()中使用了像这样

auto head = queue.getHead();

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

关于c++ - 如何从成员访问 protected /私有(private)的嵌套类指针,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44218305/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com