gpt4 book ai didi

C++ 模板化友元类

转载 作者:塔克拉玛干 更新时间:2023-11-03 01:05:51 24 4
gpt4 key购买 nike

我正在尝试用 C++ 编写一个 2-3-4 树的实现。自从我使用模板以来已经有一段时间了,而且我遇到了一些错误。这是我非常基本的代码框架:
节点.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

节点.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 节点.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’不是模板”。有人有什么想法吗?提前感谢所有建议/帮助...丹

最佳答案

已被接受的解决方案有一个小问题,即打开您的类以访问 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 {
// ...
};

关于C++ 模板化友元类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1810566/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com