У нас есть задание создать двоичное дерево поиска с некоторыми базовыми функциями. Я чувствую, что буду способен соскабливать, если бы не файлы, включенные в задание, которые нам нужно придерживаться, чтобы грейдеры могли реализовать наш код с помощью своей программы оценки. Студентам предоставляется файл под названием «Factory.cpp», который имеет функцию, которая пытается вернуть объект «BinarySearchTree» (return new BinarySearchTree();
). Однако VS 2013 дает мне ошибку, видимую в названии. После некоторых исследований я не могу найти какую-либо информацию, которую я могу реализовать в своей собственной проблеме, чтобы избавиться от ошибки. Классы шаблонов, очевидно, более абстрактны, и я не могу узнать, что включать/исключать и т. Д., Чтобы заставить все работать.return new BinarySearchTree - список аргументов для шаблона класса отсутствует
Ниже мой неполный код, который я до сих пор в моей BinarySearchTree.h:
#pragma once
#include "BSTInterface.h"
#include "NodeInterface.h"
#ifndef BINARY_SEARCH_TREE_H
#define BINARY_SEARCH_TREE_H
struct BTNode :public NodeInterface{
// Data Fields
int data;
BTNode* left;
BTNode* right;
// Constructor
BTNode(const int& the_data,
BTNode* left_val = NULL,
BTNode* right_val = NULL) :
data(the_data), left(left_val), right(right_val) {}
// Destructor (to avoid warning message)
virtual ~BTNode() {}
// Interface Functions
int getData(){
return data;
}
NodeInterface* getLeftChild(){
return left;
}
NodeInterface* getRightChild(){
return right;
}
}; // End BTNode
#include <sstream>
template<class T>
class BinarySearchTree:public BSTInterface
{
public:
BTNode* root;
// BST Constructor/Deconstructor
BinarySearchTree() : root(NULL){}
//BinarySearchTree(const int& the_data,
// const BinarySearchTree& left_child = BinarySearchTree(),
// const BinarySearchTree& right_child = BinarySearchTree()) :
// root(new BTNode(the_data, left_child.root, right_child.root)){}
virtual ~BinarySearchTree(){}
// Interface Functions ----------------------
NodeInterface* getRootNode(){
return root;
}
bool add(int data){
return addRec(root, data);
}
bool addRec(BTNode* &x, int data){
if (x == NULL){
if (Search(root, data) == true){
return false;
}
else{
root = GetNewNode(data);
return true;
}
}
if (data == x->data){
return false;
}
if (x != NULL){
if (data < x->data){
return addRec(x->left, data);
}
if (data > x->data){
return addRec(x->right, data);
}
}
}
bool remove(int data){
return false;
}
bool removeRec(BTNode* &x, int data){
return false;
}
void clear(){
}
// ------------------------------------------
// My Functions -----------------------------
BTNode* GetNewNode(int data){
BTNode* newNode = new BTNode();
newNode->data = data;
newNode->left = newNode->right = NULL;
return newNode;
}
bool Search(BTNode* root, int data) {
if (root == NULL) {
return false;
}
else if (root->data == data) {
return true;
}
else if (data < root->data) { // had <= instead
return Search(root->left, data);
}
else if (data > root->data) { // had no "if"
return Search(root->right, data);
}
}
// ------------------------------------------
};
#endif
который является производным от следующих 2-х файлов "Интерфейс":
NodeInterface.h:
//YOU MAY NOT MODIFY THIS DOCUMENT
#pragma once
#include <iostream>
class NodeInterface {
public:
NodeInterface() {}
virtual ~NodeInterface() {}
/*Returns the data that is stored in this node*/
virtual int getData() = 0;
/*Returns the left child of this node or null if it doesn't have one.*/
virtual NodeInterface * getLeftChild() = 0;
/*Returns the right child of this node or null if it doesn't have one.*/
virtual NodeInterface * getRightChild() = 0;
};
BSTInterface.h
//YOU MAY NOT MODIFY THIS DOCUMENT
#pragma once
#include "NodeInterface.h"
using namespace std;
class BSTInterface {
public:
BSTInterface() {}
virtual ~BSTInterface() {}
//Please note that the class that implements this interface must be made
//of objects which implement the NodeInterface
/*Returns the root node for this tree*/
virtual NodeInterface * getRootNode() = 0;
/*Attempts to add the given int to the BST tree*/
virtual bool add(int data) = 0;
/*Attempts to remove the given int from the BST tree*/
virtual bool remove(int data) = 0;
/*Removes all nodes from the tree, resulting in an empty tree.*/
virtual void clear() = 0;
};
Тогда они дают нам «Factory.h» и «Factory.cpp», который я считаю, что они используют, чтобы захватить нашу BinarySearchTree от того, чтобы класс, используя свою программу классификации:
Factory.h:
#include "BSTInterface.h"
using namespace std;
/*
WARNING: It is expressly forbidden to modify any part of this document, including its name
*/
class Factory
{
public:
static BSTInterface * getBST();
};
Factory.cpp:
#include "Factory.h"
#include "BinarySearchTree.h"
//You may add #include statements here
/*
You will MODIFY THIS DOCUMENT.
getBST()
Creates and returns an object whose class extends BSTInterface.
This should be an object of a class you have created.
Example: If you made a class called "BinarySearchTree", you might say, "return new BinarySearchTree();".
*/
BSTInterface * Factory::getBST()
{
return new BinarySearchTree();//Modify this line
}
в «Factory.cpp», BinarySearchTree
помечается как ошибка в VS с сообщением «список аргументов для шаблона класса отсутствует.» Как это исправить? Наряду с любыми другими ошибками вы видите.
Также, как бы объявить новый объект BinarySearchTree в main()
и вызвать его функции, чтобы проверить его?
D'oh! Я удалил эту первую строку несколько раз, прежде чем отправлять вопрос, думая, что это проблема. Но каждый раз VS подчеркивал все экземпляры 'BinarySearchTree' в файле, поэтому я сразу же возвращал строку. Однако, после того, как я сделал это на этот раз, мне просто пришлось быть терпеливым и ждать на одну секунду дольше, тогда VS выяснил, что Я делал, и подчеркнутые ошибки уходили. Приветствия ~ – velkoon