[英]C++ template instantiation, error: member of non-class type 'int'
我正在嘗試在 C++ 中實現二叉搜索樹。 我在自己的定義中遞歸調用 function Node<T>::append
時遇到了問題。
這是一個最小的可重現示例:
#include <iostream>
#include <string>
#include <memory> // std::unique_ptr<>
using namespace::std;
template<class T> class Node {
public:
// constructors
Node() {};
Node(const T&);
// operations
void append(const T&);
void print();
private:
unique_ptr<T> value, left_child, right_child;
};
template<class T> class BinaryTree {
public:
// constructors
BinaryTree() {};
BinaryTree(const T&);
// operations
void insert(const T&);
void output();
private:
Node<T> root;
int size;
};
template<class T> Node<T>::Node(const T& in): value(new T (in)), left_child(nullptr), right_child(nullptr) {}
template<class T> void Node<T>::append(const T& in) {
if (in < *value) {
if (left_child)
left_child->append(in);
else
left_child(new Node(in));
} else if (in > *value) {
if (right_child)
right_child->append(in);
else
right_child(new Node(in));
}
}
template<class T> void Node<T>::print() {
cout << string(6,' ') << "( " << *value << " ) " << endl;
if (left_child)
left_child->print();
if (right_child) {
cout << string(10,' ');
right_child->print();
}
}
template<class T> BinaryTree<T>::BinaryTree(const T& in): root(in), size(1) {}
template<class T> void BinaryTree<T>::insert(const T& in) {
root.append(in);
}
template<class T> void BinaryTree<T>::output() {
root.print();
}
int main()
{
BinaryTree<int> test(5);
test.insert(3);
test.insert(9);
test.output();
return 0;
}
g++ 記錄以下錯誤:
error: request for member 'append' in
'*((Node<int>*)this)->Node<int>::left_child.std::unique_ptr<_Tp, _Dp>::operator-><int, std::default_delete<int> >()',
which is of non-class type 'int' left_child->append(in);
我認為編譯器會看到這一行left_child->append(in);
不是作為遞歸調用,而是作為不存在的 function 的一些仿函數。
我該如何解決這個問題? 見在線編譯: https://godbolt.org/z/Pna9e5
left_child
和right_child
不指向 Node。 編譯器非常清楚地解釋了這一點:它是非類類型 'int' left_child ,left_child 是 int 類型,而不是 class。 聲明
unique_ptr<T> value, left_child, right_child;
應該
unique_ptr<T> value;
unique_ptr<Node<T>> left_child, right_child;
進一步的問題: left_child(new Node(in));
,left_child不是function,語句必須是left_child.reset(new Node(in));
.
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.