Create Point Class and overload stream insertion and stream extraction operator functions. - C++ Class

C++ examples for Class:Operator Overload

Description

Create Point Class and overload stream insertion and stream extraction operator functions.

Demo Code

#include <iostream>
class Point {// w  ww  .ja  v a2 s.c  o  m
 public:
    friend std::ostream& operator<<(std::ostream&, const Point&);
    friend std::istream& operator>>(std::istream&, Point&);

 private:
    int xCoordinate;
    int yCoordinate;
};


std::ostream& operator<<(std::ostream& out, const Point& point) {
    if (!std::cin.fail()) {
        out << point.xCoordinate << ',' << point.yCoordinate;
    }

    return out;
}

std::istream& operator>>(std::istream& in, Point& point) {
    in >> point.xCoordinate >> point.yCoordinate;

    if ((point.xCoordinate < 0 || point.xCoordinate > 9) ||
        (point.yCoordinate < 0 || point.yCoordinate > 9)) {
        in.setstate(std::ios::failbit);

        point.xCoordinate = 0;
        point.yCoordinate = 0;
    }

    return in;
}

int main(int argc, const char *argv[]) {
    Point point;

    std::cout << "Enter space separated x y coordinates: ";
    std::cin >> point;

    std::cout << "You Entered: " << point << std::endl;

    return 0;
}

Result


Related Tutorials