pt3 = 2 + pt1;
- 对于这段代码,我不知道如何重载加法运算符。
代码
//Point.h
class Point
{
private:
int x;
int y;
public:
Point() : x(NULL), y(NULL) {
std::cout << "Конструктор Point вызван\n\n";
}
Point(int x, int y) : x(x), y(y) {
std::cout << "Конструктор Point вызван\n\n";
}
~Point() {
std::cout << "Деструктор Point вызван\n\n";
}
const Point operator +(const int& a);
const Point operator +(const Point& a);
Point operator =(const Point& a);
}
//Point.cpp
const Point Point::operator+(const int& a)
{
Point temp;
temp.x = this->x + a;
temp.y = this->y + a;
return temp;
}
const Point Point::operator+(const Point& a)
{
Point temp;
temp.x = this->x + a.x;
temp.y = this->y + a.y;
return temp;
}
Point Point::operator =(const Point& a) {
this->x = a.x;
this->y = a.y;
return *this;
}
//main.cpp
int main() {
Point pt1(1,1);
Point pt2(2,2);
Point pt3;
pt3 = pt1 + 5;
pt3 = 2 + pt1;
pt3 = pt1 + pt2;
return 0;
}