C++ 主C+;中包含的不同类的相同函数+;
正如您可能已经从标题中注意到的,我有不同的类,特别是3个,每个类都响应不同的树实现 在树1.h中C++ 主C+;中包含的不同类的相同函数+;,c++,function,class,tree,include,C++,Function,Class,Tree,Include,正如您可能已经从标题中注意到的,我有不同的类,特别是3个,每个类都响应不同的树实现 在树1.h中 class Tree1 { public: struct node{ char label; node* nHMI_ptr; node* nHD_ptr; }; node* root; Tree1(); ~Tree1(); bool Empty(); Tree1::node&a
class Tree1 {
public:
struct node{
char label;
node* nHMI_ptr;
node* nHD_ptr;
};
node* root;
Tree1();
~Tree1();
bool Empty();
Tree1::node& Root();
void AddSon(int i, node &n, char l);
/*
*
* (other functions)
*/
}
在树2.h中
class Tree2 {
public:
struct node{
char label;
node* nHMI_ptr;
node* nHD_ptr;
node* nFather_ptr;
node* nHI_ptr;
};
node* root;
Tree2();
~Tree2();
bool Empty();
Tree2::node& Root();
void AddSon(int i, node &n, char l);
/*
*
* (other functions)
*/
}
在树3.h中
class Tree3{
public:
Tree3();
~Tree3();
struct node;
struct nodeSon{
struct node* node_ptr;
nodeSon* nextNodeSon_ptr;
};
struct node{
char label;
node* nextNode_ptr;
struct nodeSon* nSon;
};
node* root;
bool Empty();
Tree3::node& Root();
void AddSon(int i, node &n, char l);
/*
*
* (other functions)
*/
}
正如您所看到的,它们具有相同名称或标识符下的函数和成员。这是因为我想使用这个函数来生成各种更复杂的算法,但棘手的是,我想使这个算法独立于所使用的类。我想到的第一件事是在main.cpp上创建这个算法
In main.cpp
#include <cstdlib>
#include <iostream>
#include "Tree1.h"
//#include "Tree2.h"
//#include "Tree3.h"
void someFunc(node n) {
//do something by calling Tree functions
//E.g. call Empty(), call AddSon(...)
}
int main(int argc, char** argv) {
return 0;
}
#包括
#包括
#包括“Tree1.h”
//#包括“Tree2.h”
//#包括“Tree3.h”
void someFunc(节点n){
//通过调用树函数来做一些事情
//例如,调用Empty(),调用AddSon(…)
}
int main(int argc,字符**argv){
返回0;
}
我试图实现的是,someFunc(…)可以在所有树上工作,而无需更改任何底层代码,只需启用其中一个#include并禁用另外两个
- 有可能吗
- 我怎样才能做到这一点
- 有可能吗
- 我怎样才能做到这一点
template<class TreeType>
void someFunc(TreeType& treeContext, typename TreeType::node& n) {
//do something by calling Tree functions
//E.g. call Empty(), call AddSon(...)
}
模板
void someFunc(TreeType&treeContext,typename TreeType::node&n){
//通过调用树函数来做一些事情
//例如,调用Empty(),调用AddSon(…)
}
DR;TL;使用模板创建someFunc
的通用版本。还可以让各种树类从纯虚拟类BaseTree继承,后者定义所有常见的树功能,然后调用void someFunc(BaseTree&tree,node n)
@user4581301 Nope<代码>节点不能在运行时推导,除非它已经在基类中声明。啊,废话。你说得对。类中嵌入了节点的各种定义。对不起,这是一个很好的方法。谢谢!;)