c ++模板朋友类

时间:2009-11-27 20:39:50

标签: c++ class templates g++ friend

我正在尝试用c ++编写2-3-4树的实现。我已经有一段时间了,因为我使用过模板,而且我遇到了一些错误。这是我非常基本的代码框架:
    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'不是模板”。有没有人有任何想法?感谢所有建议/帮助提前... 丹

2 个答案:

答案 0 :(得分:8)

已接受的解决方案存在轻微的问题,即将您的类打开到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 {
   // ...
};

答案 1 :(得分:5)

使用friend关键字时,只需将其声明为模板即可。您在代码中使用了不正确的语法来表示朋友声明。你想写的是:

template <class U> friend class TwoThreeFourTree;