ostream

Модераторы: Hawk, Romeo, Absurd, DeeJayC, WinMain

Ответить
Lotles
Сообщения: 59
Зарегистрирован: 03 июл 2010, 12:42

Код: Выделить всё

#include "stdafx.h"
#include <conio.h>
using namespace std;

class Point {
private:             // Data members (private)
    int x, y;
public:              // Constructors
    Point() {};
    Point(int new_x, int new_y) {set(new_x, new_y);}
    Point(const Point &src) {set(src.x, src.y);}

// Operations

    Point add(const Point &pt);
    Point sub(const Point &pt);
    Point operator+(const Point &pt) {return add(pt);}
    Point operator-(const Point &pt) {return sub(pt);}

    friend ostream &operator<<(ostream &os, Point &pt);  // FUNCTION DECLARED

// Other member functions

    void set(int new_x, int new_y);
    int get_x() const {return x;}
    int get_y() const {return y;}
};

int main() {

    Point point1(20, 20);
    Point point2(0, 5);
    Point point3(-10, 25);
    Point point4 = point1 + point2 + point3;

    cout << "The point is " << point4 << endl;  // TEST OPERATOR<< FUNCT.

    return 0;
}

void Point::set(int new_x, int new_y) {
    if (new_x < 0)
        new_x *= -1;
    if (new_y < 0)
        new_y *= -1;
    x = new_x;
    y = new_y;
}

Point Point::add(const Point &pt) {
    Point new_pt;
    new_pt.x = x + pt.x;
    new_pt.y = y + pt.y;
    return new_pt;
}

Point Point::sub(const Point &pt) {
    Point new_pt;
    new_pt.x = x - pt.x;
    new_pt.y = y - pt.y;
    return new_pt;
}

ostream &operator<<(ostream &os, Point &pt) { // FUNCTION DEFINITION
    os << "(" << pt.x << ", " << pt.y << ")";
    return os;
}  


Вот строка

Код: Выделить всё

    cout << "The point is " << point4 << endl;  // TEST OPERATOR<< FUNCT.
после нее выз-ся это

Код: Выделить всё

ostream &operator<<(ostream &os, Point &pt) { // FUNCTION DEFINITION
    os << "(" << pt.x << ", " << pt.y << ")";
    return os;
}
Что такое os(как я понял это и есть cout по-большому счету)
Аватара пользователя
Decoder
Сообщения: 308
Зарегистрирован: 19 фев 2008, 23:11
Откуда: Moscow

В качестве параметра ostream &os может передаваться любой класс, производный от ostream. Это может быть файловый поток ofstream, поток строки ostrstream или поток вывода на консоль cout, как в твоём примере.
Поумнеть несложно, куда труднее от дури избавиться.
Ответить