vs2010 类模板 friend 函数无法调用类的private 模板类,模板函数

学习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;

}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值