最近在看侯捷的C++对象模型,顺便把他的例子也做了一遍便于深刻理解C++模型,例子如下:头文件
#ifndef MODEL_H
#define MODEL_H
#include <iostream>
#include <ostream>
using namespace std;
template<class type, int dim>
class Point{
public:
Point(type coords[dim]);
Point();
type& operator[](int index) const;
Point<type,dim> operator + (Point<type,dim>& p2);
friend
ostream & operator << (ostream &ios, const Point<type, dim> &pt)
{
ios << "(";
for (int i = 0; i < dim; ++i)
ios << pt.m_coords[i] << " ";
ios << ")";
return ios;
}
private:
type m_coords[dim];
};
#endif
CPP文件
#include "model.h"
template<class type, int dim>
Point<type,dim>::Point(type coords[dim])
{
for (int i = 0; i < dim; ++i)
{
m_coords[i] = coords[i];
}
}
template<class type, int dim>
Point<type, dim>::Point()
{
;
}
template<class type, int dim>
type& Point<type, dim>::operator[](int index) const
{
return m_coords[index];
}
template<class type, int dim>
Point<type, dim> Point<type, dim>::operator + (Point<type, dim>& p2)
{
Point tmp;
for (int i = 0; i < dim; ++i)
{
tmp.m_coords[i] = m_coords[i] + p2.m_coords[i];
}
return tmp;
}
int main()
{
Point<int, 10> kk;
cout << kk;
getchar();
return 0;
}
结果
这里有个奇怪的问题,就是当我把 运算符 << 重载在cpp文件中实现的时候,就会报错,实现如下:
template<class type, int dim>
ostream & operator << (ostream &ios, const Point<type, dim> &pt)
{
ios << "(";
for (int i = 0; i < dim; ++i)
ios << pt.m_coords[i] << " ";
ios << ")";
return ios;
}
报错如下
Error 1 error LNK2019: unresolved external symbol "class std::basic_ostream<char,struct std::char_traits<char> > & __cdecl operator<<(class std::basic_ostream<char,struct std::char_traits<char> > &,class Point<int,10> const &)" (??6@YAAAV?$basic_ostream@DU?$char_traits@D@std@@@std@@AAV01@ABV?$Point@H$09@@@Z) referenced in function _main D:\visual studio 2013\Projects\ConsoleApplication1\plusModel\plusModel\model.obj plusModel
我不知道是不是因为友元的重载,在cpp文件实现的时候就当作了全局函数重载而导致原来运算符 << 出现问题的原因,还请大神们指点,谢谢