学习c++数据结构和算法 回溯算法遇到的问题:
1.在运行实例时候,friend 函数无法调用类的private ,
原因: 模板函数声明为friend的时候 要 用模板函数的方式 friend T MaxLoading<T>(T w[], T c, int n); 不能像普通函数那样写,否则vs2010 不能认出这是模板函数。尽管是在类声明之前 声明了 该模板函数同样不行。
2.无法解析的外部符号问题, 不能正常调用类的成员函数。
原因:之前我把 该模板类的函数写在了.cpp文件里,后来查了一下才知道模板类的成员函数应该放在.h文件里,模板类学完了很久没用这些细节都忘了。
附源代码:货箱装船的问题
//
//
//Loading.h
//
#ifndef LOADING_H
#define LOADING_H
template<class T>
T MaxLoading(T w[], T c, int n);
template<class T>
class Loading{
public:
friend T MaxLoading<T>(T w[], T c, int n);
private:
void maxLoading(int i);
int n; //货箱数目
T *w, //货船重量数组
c, //第一艘船的重量
cw, //当前装载的重量
bestw; //目前最优装载的重量
};
template<class T>
void Loading<T>::maxLoading(int i)
{
//从第i层节点搜索
if(i > n)
{//位于叶节点
if(cw > bestw) bestw = cw;
return;
}
//检查子树
if(cw + w[i] <=c)
{//尝试x[i] = 1
cw += w[i];
maxLoading(i+1);
cw -= w[i];
}
maxLoading(i+1);//尝试x[i] = 0
}
#endif //Loading.h
——————————————————————————————————
//
//
//main.cpp
//
#include <iostream>
#include "Loading.h"
using std::cin;
using std::cout;
using std::endl;
template<class T>
T MaxLoading(T w[], T c, int n)
{
Loading<T> x;
x.w = w;
x.c = c;
x.n = n;
x.bestw = 0;
x.cw = 0;
x.maxLoading(1);
return x.bestw;
}
int main(int argc, char* argv[])
{
int n = 4;
int c = 12;
int w2[4]= {8,6,2,3};
cout << MaxLoading(w2,c,n) <<endl;
/
char ch;
cin>> ch;
return 0;
}