今天在
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 ==========
![](http://hi.csdn.net/attachment/201107/4/0_1309778107HHH9.gif)
按照原先的定义形式的话,在main函数中使用了类型检查将A转换为T。可是为什么在声明的时候就一定要用到一个类A的参数呢?
按照我现在的理论知识来说,这个是没有错误的,但是恰恰在声明的时候一定要使用类A的一个参数才可以,为什么呢?