类模板与友元函数链接问题

测试环境:windows 7 vs2013

1.代码

#include<iostream>

template<class T>
class Test
{
private:
	T m_x;

public:
	friend void print(const Test<T> &test);
	Test(T x) :m_x(x)
	{
	}
};
template<class T>
 void print(const Test<T> &test)
{
	std::cout << test.m_x<< std::endl;
};
int main()
{
	Test<int> test(1);
	print(test);

	std::cin.get();
	return 0;
}

上面的程序编译没有问题,链接时候会报如下的错误,错误    2    error LNK1120: 1 个无法解析的外部命令,错误  1  error LNK2019: 无法解析的外部符号 "void __cdecl print(class Test<int> const &)" (?print@@YAXABV?$Test@H@@@Z),该符号在函数 _main 中被引用 。

解决办法有两种

1.将友元函数放入函数内部

#include<iostream>

template<class T>
class Test
{
private:
	T m_x;

public:
	friend void print(const Test<T> &test)
	{
		std::cout << test.m_x << std::endl;
	}
	Test(T x) :m_x(x)
	{
	}
};

int main()
{
	Test<int> test(1);
	print(test);

	std::cin.get();
	return 0;
}

2.仍旧放在外部,采取声明等方式

#include<iostream>

template<class T>
class Test;
template<class T>
void print(const Test<T> &test);

template<class T>
class Test
{
private:
	T m_x;

public:
	friend void print<T>(const Test<T> &test);//这里<T>必不可少
	Test(T x) :m_x(x)
	{
	}
};
template<class T>
 void print(const Test<T> &test)
{
	std::cout << test.m_x<< std::endl;
};
int main()
{
	Test<int> test(1);
	print(test);

	std::cin.get();
	return 0;
}

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值