Operator overloaded是C++獨特的功能,能夠把operator重新定義,符合class的需求,但是在定義的時候要注意是否違反class原本的意義。
- Rule of thumb, if a class needs a destructor, it will also need the assignment operator and a copy constructor. C++ Primer P.485
- If the operator often does the same work, the common work should be put in private utility functions.
- #include <iostream>
- #include <cstdlib>
- using namespace std;
- //////////////////////////////////////////////////////
- class Point{
- public:
- //constructor
- Point(double xval=0.0, double yval=0.0):
- x(xval), y(yval){}
-
- //copy constructor
- Point(const Point &rhs):
- x(rhs.x), y(rhs.y){}
-
- //destructor
- ~Point(){}
-
- //must return a new object
- friend Point
- operator+ (const Point &lhs, const Point &rhs){
- Point ret(lhs);
- //call overloaded operator +=
- ret += rhs;
- return ret;
- }
-
- //must return reference
- Point& operator+= (const Point &rhs){
- this->x += rhs.x;
- this->y += rhs.y;
- return *this;
- }
-
- //prefix operator,return a reference
- Point& operator++ (){
- this->x += 1.0;
- this->y += 1.0;
- return *this;
- }
-
- //posfix operator++, return a new object
- Point operator++(int){
- Point ret(*this);
- ++*this;
- return ret;
- }
-
- friend inline bool
- operator== (const Point &lhs, const Point &rhs){
- return lhs.x == rhs.x && lhs.y == rhs.y;
- }
-
- friend inline bool
- operator!= (const Point &lhs, const Point &rhs){
- return !(lhs == rhs);
- }
-
- //input operators must deal with errors and EOF
- friend istream&
- operator>> (istream &in, Point &obj){
- in>>obj.x>>obj.y;
- if(!in)
- obj = Point();
- return in;
- }
-
- //IO operators must be nomember functions
- //should not print a newline
- friend ostream&
- operator<< (ostream &os, const Point &obj){
- os<<"("<<obj.x<<", "<<obj.y<<")";
- return os;
- }
-
- private:
- double x, y;
- };
- //////////////////////////////////////////////////////
-