0
我有一個圖形類,下面簡單的實現創建子二進制樹節點類班,但我很難找出如何做到這一點。我寫了一個不完整的類,但是我收到了幾個編譯錯誤。下面是代碼:從模板圖形節點類
#include <iostream>
#include <vector>
using namespace std;
template <typename T>
class GraphNode {
public:
T data;
vector<GraphNode*> adj;
void Print(GraphNode<T>* node) {
if(!node) {
std::cout << "*";
return;
}
std::cout << node->data << ":";
for(typename vector<GraphNode<T>* >::iterator iter = adj.begin();
iter != adj.end();
iter++)
{
Print(iter);
}
}
};
template <typename T>
class BinaryTreeNode : public GraphNode<T> {
using GraphNode<T>::data;
using GraphNode<T>::adj;
public:
BinaryTreeNode<T>* lhs;
BinaryTreeNode<T>* rhs;
BinaryTreeNode() {
adj.push_back(NULL);
adj.push_back(NULL);
lhs = NULL;
rhs = NULL;
}
BinaryTreeNode(T in_data) {
data = in_data;
adj.push_back(NULL);
adj.push_back(NULL);
lhs = NULL;
rhs = NULL;
}
BinaryTreeNode& operator=(const BinaryTreeNode& other) {
// if the other item is this, then return itself
if(&other != this) {
data = other.data;
// copy the vector
lhs = other.lhs;
rhs = other.rhs;
}
return *this;
}
};
int main() {
BinaryTreeNode<int> node;
cout << 42;
return 0;
}
請注意,您試圖:
template <typename T>
// Binary Tree Node
class BinaryTreeNode : public GraphNode<T> {
public:
BinaryTreeNode<T>* lhs;
BinaryTreeNode<T>* rhs;
BinaryTreeNode() {
adj.push_back(NULL);
adj.push_back(NULL);
lhs = adj[0];
rhs = adj[1];
}
BinaryTreeNode(T in_data) {
data = in_data;
adj.push_back(NULL);
adj.push_back(NULL);
lhs = adj[0];
rhs = adj[1];
}
BinaryTreeNode& operator=(const BinaryTreeNode& other) {
// if the other item is this, then return itself
if(&other != this) {
data = other.data;
// copy the vector
lhs = other.lhs;
rhs = other.rhs;
}
return *this;
}
};
錯誤
../src/BinaryTree.h:22:3: error: ‘adj’ was not declared in this scope
../src/BinaryTree.h:30:3: error: ‘data’ was not declared in this scope
雖然,實際上,我認爲在http://stackoverflow.com/q/32665178/995218的解釋更好。 – atkins