c++ - C++ 模板实例化,错误:非类类型“int”的成员
问题描述
我正在尝试在 C++ 中实现二叉搜索树。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);
不会将该行视为递归调用,而是将其视为某个不存在的函数的仿函数。
我该如何解决这个问题?见在线编译:https ://godbolt.org/z/Pna9e5
解决方案
left_child
并且right_child
不要指向节点。编译器非常清楚地解释了这一点:它是非类类型 'int' left_child, left_child 是 int 类型,而不是类。声明
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 不是函数,语句必须是left_child.reset(new Node(in));
.
推荐阅读
- wordpress - 编辑 htaccess 文件以仅重定向内容 + Wordpress
- javascript - 在可序列化的 dto 上嵌套自定义名称
- c - 如何确定编译器何时缓存值而不是从正确的寄存器或内存位置读取它们?
- javascript - 试图理解为什么这个“while”循环在 React/JSX/node 中不能按预期工作?
- java - jdk 警告:计划从未来的 JDK 版本中删除 Nashorn 引擎
- python - 带有 XGBoost 和使用 eval_set 的 DaskML 需要预先计算的数据
- javascript - 无法在 Gitlab 页面上访问我的 Svelte 组件名称
- c++ - 一位朋友给了我他的源代码,但我无法修复 FNVHash 中的错误
- html - 使用css在div中隐藏第一个跨度和标签
- angularjs - 如何仅更改 D3.js 图表中数据网格或 x 和 y 轴的颜色