#include <iostream>
using namespace std;
class Point {
private:
int x, y; // Private data members
public:
Point(int x = 0, int y = 0); // Constructor
int getX() const; // Getters
int getY() const;
void setX(int x); // Setters
void setY(int y);
void print() const;
const Point operator+(const Point & rhs);
// Overload '+' operator as member function of the class
};
int main(int argc, char** argv)
{
Point p1(1, 2), p2(4, 5);
// Use overloaded operator +
Point p3 = p1 + p2;
p1.print(); // (1,2)
p2.print(); // (4,5)
p3.print(); // (5,7)
// Invoke via usual dot syntax, same as p1+p2
Point p4 = p1.operator+(p2);
p4.print(); // (5,7)
// Chaining
Point p5 = p1 + p2 + p3 + p4;
p5.print(); // (15,21)
return 0;
}
// Constructor - The default values are specified in the declaration
Point::Point(int x, int y) : x(x), y(y) { } // Using initializer list
// Getters
int Point::getX() const { return x; }
int Point::getY() const { return y; }
// Setters
void Point::setX(int x) { this->x
= x; } // (*this).x = x; x = x
void Point::setY(int y) { this->y = y; }
// Public Functions
void Point::print() const {
cout << "(" << x << "," << y << ")" << endl;
}
// Member function overloading '+' operator
const Point Point::operator+(const Point & rhs) {
return Point(x + rhs.x, y + rhs.y);
}
我正在研究运算符重载,但我不明白为什么会收到错误。
error: no match for 'operator+' (operand types are 'const Point' and 'Point')
为了理解它,我故意删除了 operator+
函数末尾的 const
限定符。有人可以明确解释为什么我需要它吗?
最佳答案
成员(member)
const Point Point::operator+(const Point & rhs);
是一个非常量成员,即要求操作的 lhs 是可变的,但是(如错误消息所示)您需要带有 const
的操作嗯。因此,您必须这样声明运算符
Point Point::operator+(const Point & rhs) const;
请注意,我还删除了 const
对于返回类型,因为它已被弃用。
为什么您需要 const
?自然+
运算符(例如算术类型之间)不会更改其参数,因此,使用此运算符的通常(人类)约定隐式假定参数未更改。在您的特定情况下,返回 a+b
明确是const
(尽管据我所知,这已被弃用),因此在 a+b+c
中=(a+b)+c
左侧是 const
并且您的非常量成员函数无法使用。
此外,只要成员函数不改变其对象的状态,就应该声明 const
,这样就可以调用 const
对象。
或者,可以将此运算符定义为非成员函数友元
Point operator+(const Point&lhs, const Point&rhs);
它更清楚地表达了 lhs 和 rhs 之间的对称性(非常量成员的相应函数是
Point operator+(Point&lhs, const Point&rhs);
)。
关于c++ - const 限定符 函数结束,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33362783/