gpt4 book ai didi

c++ - "is private within this context"被抛出用于不应该是私有(private)的函数(GCC 5.3.0,C++11)

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

我正在尝试创建一个队列,这需要创建存储在队列中的另一个对象。错误是

binary.cpp: In function ‘int main()’:
binary.cpp:183:1: error: ‘Queue<T>::Queue(T) [with T = binary<std::basic_string<char> >*]’ is private
Queue<T>::Queue(T item){
^
binary.cpp:286:65: error: within this context
Queue<binary<string>*>* queue = new Queue<binary<string>*>(tree);
^

binary.cpp: In instantiation of ‘Queue<T>::Queue(T) [with T = binary<std::basic_string<char> >*]’:
binary.cpp:286:65: required from here
binary.cpp:132:1: error: ‘Link<T>::Link(T) [with T = binary<std::basic_string<char> >*]’ is private
Link<T>::Link(T item){
^
binary.cpp:184:7: error: within this context
head = new Link<T>(item);

第一个是Queue的实例化,第二个来自Queue的构造函数,在第一个错误的实例化行调用。重要的声明和定义是:

template<class T>
class Link{
Link(T item);

private:
T content;
Link<T>* next;
};

template<class T>
Link<T>::Link(T item){
content = item;
next = NULL;
}

template<class T>
class Queue{
Queue();
Queue(T item);

private:
Link<T>* head;
Link<T>* end;
int length;
};

template<class T>
Queue<T>::Queue(T item){
head = new Link<T>(item);
end = head;
length = 1;
}

Link 类在 Queue 类之前声明和定义,两者都在代码中使用之前声明和定义。感谢您的宝贵时间。

最佳答案

默认情况下类成员是私有(private)的,即使你使用 private稍后访问说明符,您的代码如下:

template<class T>
class Queue{
Queue(); //Implicitly private
Queue(T item); //Implicitly private

private: //explicit private
Link<T>* head;
Link<T>* end;
int length;
};

所以你需要公开构造函数:

template<class T>
class Queue{
public:
Queue();
Queue(T item);
private:
Link<T>* head;
Link<T>* end;
int length;
};

同样适用于 Link<T>类模板。

关于c++ - "is private within this context"被抛出用于不应该是私有(private)的函数(GCC 5.3.0,C++11),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36168718/

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