#include <iostream>
using namespace std;
template <typename T>
// we shouln't use the template here, it will cause a bug
// "argument list for class template "Node" is missingC/C++(441)"
// to fix the bug, check "https://stackoverflow.com/questions/15283195/argument-list-for-class-template-is-missing"
struct Node
{
T datum;
Node* left;
Node* right;
};
// REQUIRES: node represents a valid tree
// MODIFIES: cout
// EFFECTS: Prints each element in the given tree to stanhdard out
// with each element followed by a space
void print(const Node *tree) {
if(tree) { // non-empty tree
cout << tree->datum << " ";
print(tree->left);
print(tree->right);
}
}
Я новичок в C++, я пытался изучить основы печати двоичного дерева, я не знаю, как исправить красную строку под Node
в void print(const Node *tree)
, я видел, как некоторые люди говорили, что преобразование шаблона T в int исправит ошибку, но я не знаю, почему это работает.
О, спасибо за инструкцию, буду следовать.
Функция печати также должна быть функцией шаблона, компилятору С++ нужно, чтобы вы сообщили ему конкретный тип функции Node in print. Смотри ниже:
#include <iostream>
using namespace std;
template<typename T>
struct Node
{
T datum;
Node* left;
Node* right;
};
template<typename T>
void print(const Node<T>* tree) {
if (tree == nullptr) {
return;
}
print(tree->left);
cout << tree->datum << " ";
print(tree->right);
}
Привет! Разместите свой код в виде форматированного текста, а не изображения: meta.stackoverflow.com/questions/285551/…