C++ template 问题

今天在

http://bbs.51cto.com/viewthread.php?tid=854253&pid=4320845&page=1&extra=#pid4320845

看到了一个关于C++template的问题,于是就仔细的研究过了一下。

#include <iostream>
using namespace std;
template<class T>
class A
{
public:
	A(){m_value = 1;}
	friend T operator+(const A& left, const T& right);
	int m_value;
};
template<class T>
T operator+(const T& left, const T& right)
{
	T result;
	result.m_value = left.m_value + right.m_value;
	return result;
}
int main(int argc, char* argv[])
{
	A<int> a;
	A<int> b;
	A<int> c  = a + b;
	cout << c.m_value << endl;
	system("pause");
	return 0;
}

上面的代码在vs2008里面没有错误

========== Build: 1 succeeded, 0 failed, 0 up-to-date, 0 skipped ==========

我把同样的代码放到linux里面测试一下:



编译结果有错:


但是已经有可执行文件生成了,而且执行结果正确:





刚好这段时间在研究C++的template,看了半天也没看出端倪来。


前面的第一段代码,在类体中声明的时候使用的是

friend T operator+(const A& left, const T& right);

而在定义的时候使用

T operator+(const T& left, const T& right)

并且此处只能这么声明和定义,不然就错误了

如如此声明:

	friend T operator+(const T& left, const T& right);
错误如下:

Compiling...
1>main.cpp
1>d:\documents\visual studio 2008\projects\demo_template\demo_template\main.cpp(8) : error C2803: 'operator +' must have at least one formal parameter of class type
1>        d:\documents\visual studio 2008\projects\demo_template\demo_template\main.cpp(20) : see reference to class template instantiation 'A<T>' being compiled
1>        with
1>        [
1>            T=int
1>        ]
1>Build log was saved at "file://d:\documents\Visual Studio 2008\Projects\demo_template\demo_template\Debug\BuildLog.htm"
1>demo_template - 1 error(s), 0 warning(s)
========== Build: 0 succeeded, 1 failed, 0 up-to-date, 0 skipped ==========

按照原先的定义形式的话,在main函数中使用了类型检查将A转换为T。可是为什么在声明的时候就一定要用到一个类A的参数呢?

按照我现在的理论知识来说,这个是没有错误的,但是恰恰在声明的时候一定要使用类A的一个参数才可以,为什么呢?

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 3
    评论
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值