шаблонный класс с ++ - PullRequest
       22

шаблонный класс с ++

4 голосов
/ 27 ноября 2009

Я пытаюсь написать реализацию дерева 2-3-4 в c ++. Я давно не пользовался шаблонами, и у меня появляются некоторые ошибки. Вот мой чрезвычайно простой каркас кода:
node.h:

    #ifndef TTFNODE_H  
    #define TTFNODE_H  
    template <class T>  
    class TreeNode  
    {  
      private:  
      TreeNode();  
      TreeNode(T item);  
      T data[3];  
      TreeNode<T>* child[4];  
      friend class TwoThreeFourTree<T>;   
      int nodeType;  
    };  
    #endif

node.cpp:

#include "node.h"

using namespace std;
template <class T>
//default constructor
TreeNode<T>::TreeNode(){
}

template <class T>
//paramerter receving constructor
TreeNode<T>::TreeNode(T item){
data[0] = item;
nodeType = 2;
}

TwoThreeFourTree.h

#include "node.h"
#ifndef TWO_H
#define TWO_H
enum result {same, leaf,lchild,lmchild,rmchild, rchild};
template <class T> class TwoThreeFourTree
{
  public:
    TwoThreeFourTree();

  private:
    TreeNode<T> * root;
};
#endif

TwoThreeFourTree.cpp:

#include "TwoThreeFourTree.h"
#include <iostream>
#include <string>

using namespace std;

template <class T>
TwoThreeFourTree<T>::TwoThreeFourTree(){
  root = NULL;
}

И main.cpp:

#include "TwoThreeFourTree.h"
#include <string>
#include <iostream>
#include <fstream>

using namespace std;

int main(){
  ifstream inFile;
  string filename = "numbers.txt";
  inFile.open (filename.c_str());
  int curInt = 0;
  TwoThreeFourTree <TreeNode> Tree;

  while(!inFile.eof()){
    inFile >> curInt;
    cout << curInt << " " << endl;
  }

  inFile.close();
}

И когда я пытаюсь скомпилировать из командной строки: g ++ main.cpp node.cpp TwoThreeFourTree.cpp

Я получаю следующие ошибки:

In file included from TwoThreeFourTree.h:1,  
             from main.cpp:1:  
node.h:12: error: ‘TwoThreeFourTree’ is not a template  
main.cpp: In function ‘int main()’:  
main.cpp:13: error: type/value mismatch at argument 1 in template parameter list for ‘template<class T> class TwoThreeFourTree’  
main.cpp:13: error:   expected a type, got ‘TreeNode’  
main.cpp:13: error: invalid type in declaration before ‘;’ token  
In file included from node.cpp:1:  
node.h:12: error: ‘TwoThreeFourTree’ is not a template  
In file included from TwoThreeFourTree.h:1,  
             from TwoThreeFourTree.cpp:1:  
node.h:12: error: ‘TwoThreeFourTree’ is not a template  

Мой главный вопрос: почему написано «ошибка: TwoThreeFourTree’ не шаблон » У кого-нибудь есть какие-либо идеи? Спасибо за все советы / помощь заранее ... Dan

Ответы [ 2 ]

8 голосов
/ 28 ноября 2009

В принятом решении есть небольшая проблема - открыть свой класс для любого экземпляра шаблона TwoThreeFourTree, а не только для тех, которые имеют один и тот же тип экземпляра.

Если вы хотите открыть класс только для экземпляров того же типа, вы можете использовать следующий синтаксис:

template <typename T> class TwoThreeFourTree; // forward declare the other template
template <typename T>
class TreeNode {
   friend class TwoThreeFourTree<T>;
   // ...
};
template <typename T>
class TwoThreeFourTree {
   // ...
};
5 голосов
/ 27 ноября 2009

Вам просто нужно объявить его как шаблон, когда вы используете ключевое слово friend. Вы используете неверный синтаксис для объявления друга в вашем коде. То, что вы хотите написать:

template <class U> friend class TwoThreeFourTree;
...