Van*_*ana 4 c++ templates class
我编写了一个程序,使用 C++ 类将排序数组转换为 BST。我收到以下错误:
error C2143: syntax error : missing ';' before '*'
error C4430: missing type specifier - int assumed. Note: C++ does not support default-int
error C2065: 'T' : undeclared identifier
error C2923: 'Binary_Search_Tree' : 'T' is not a valid template type argument for parameter 'T'
Run Code Online (Sandbox Code Playgroud)
以下是我的程序:
template <class T>
class Binary_Search_Tree {
public:
struct Bst_Node {
T value;
Bst_Node* left;
Bst_Node* right;
};
Bst_Node* root;
Binary_Search_Tree();
Bst_Node* sortedarraytobst(T* A, int start, int end);
};
template <class T> Binary_Search_Tree<T>::Binary_Search_Tree() {
root = nullptr;
std::cout << "Constructor called" << std::endl;
}
template <class T> Bst_Node* Binary_Search_Tree<T>::sortedarraytobst(T* A, int start, int end) {
if(start > end)
return NULL;
int mid = start + (end - start)/2;
Bst_Node* newnode = new Bst_Node();
newnode->value = A[mid];
newnode->left = sortedarraytobst(A,start,mid-1);
newnode->right = sortedarraytobst(A,mid+1,end);
return newnode;
}
int main()
{
Binary_Search_Tree<int> tree;
int Array[10] = {1,2,5,6,8,9,12};
int n = sizeof(Array)/sizeof(Array[0]);
tree.root = tree.sortedarraytobst(Array,0,n-1);
return 0;
}
Run Code Online (Sandbox Code Playgroud)
请求这方面的帮助。我发现模板的使用非常令人困惑。
在实现的返回值中sortedarraytobst,您应该替换Bst_Node*为typename Binary_Search_Tree<T>::Bst_Node*. 当作为返回类型放置时,它被视为“类外部”,因此无法解析Bst_Node*.