首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 开发语言 > C++ >

重载+,+=解决方案

2012-03-01 
重载+,+我定义了模版类Point,定义和实现都在一个Point.h文件中同时用友元重载了+,+,#includePoint.h u

重载+,+=
我定义了模版类Point,定义和实现都在一个Point.h文件中
同时用   友元   重载了+,+=,

#include   "Point.h "
using   Geometry::Point;
int   main()
{
Point <int>   p1(1,   2);
Point <int>   p2(3,   4);

p1   +=   p2;
                 
                  return   0;
}  

链接出错:
error   LNK2019:   unresolved   external   symbol   "class   Geometry::Point <int>   &   __cdecl   Geometry::operator+=(...)

请问是什么原因?,难道是友元函数的关系?


[解决办法]
template <class T>
struct Point {

T x;
T y;

Point(T x, T y)
{
this-> x = x;
this-> y = y;
}

Point& operator+=(const Point& p)
{
x += p.x;
y += p.y;

return *this;
}

};

[解决办法]
你上面的的是在cpp里,还是.h里,如果是cpp里请移到.h
[解决办法]
贴全代码吧。
[解决办法]
把operator += 定义在外面咋都不行,定义在里面好了

template <class T> class Point {
public:
T x;
T y;

Point(T x, T y) {
this-> x = x;
this-> y = y;
}

friend Point <T> & operator +=(Point <T> & point1, const Point <T> & point2) {
point1.x += point2.x;
point1.y += point2.y;

return point1;

}
};


或者可以直接把它定义成成员

template <class T> class Point {
public:
T x;
T y;

Point(T x, T y) {
this-> x = x;
this-> y = y;
}

Point& operator +=(const Point& point) {
this-> x += point.x;
this-> y += point.y;

return *this;

}
};

热点排行