How do C ++ threads work?

I would like to know how C ++ stream classes work. When you speak:

cout<<"Hello\n";

What exactly does "<<" do. I know that cout is an iostream object form representing a standard narrow-character output (char) output stream.

In C "<is a bitwise shift operator, so it moves bits to the left, and in C ++ it is an insertion operator. It's good that all I know, I really don’t understand how it works under the hood.

What I'm asking for is a detailed explanation about C ++ stream classes, how they are defined and implemented.

Thank you very much for your time and sorry for my english.

+4
source share
3 answers

, cout ( ).

#include <string>

class os_t {
    public:
        os_t & operator<<(std::string const & s) {
            printf("%s", s.c_str());
            return *this;
        }
};

int main() {
    os_t os;

    os << "hello\n";
    os << "chaining " << "works too." << "\n";
}

:

  • operator<< - , operator+ .
  • , : return *this;.

, os_t, - ?

- . . , :

#include <string>

class os_t {
    public:
        os_t & operator<<(std::string const & s) {
            printf("%s", s.c_str());
            return *this;
        }
};

os_t & operator<<(os_t & os, int x) {
    printf("%d", x);
    return os;

    // We could also have used the class functionality to do this:
    // os << std::to_string(x);
    // return os;
}

int main() {
    os_t os;

    os << "now we can also print integers: " << 3 << "\n";
}

?

, , GMP. . , . . , , , int.

#include <iostream>
#include <gmpxx.h>

int main() {
    mpz_class x("7612058254738945");
    mpz_class y("9263591128439081");

    x = x + y * y;
    y = x << 2;

    std::cout << x + y << std::endl;
}
+7

<< ++ , , .

C , 1 << 3 - , 8. int operator<<(int, int), 1 3 8.

, operator<< - . .

++ << -. cout << "Hello!", ostream & operator<< (ostream & output, char const * stream_me). ostream &. , std::cout << "Hello World" << "!";, operator<<... std:: cout "Hello World", "!".

, class Foo, , , ostream & operator<< (ostream & output, Foo const & print_me). .

#include <iostream>

struct Circle {
  float x, y;
  float radius;
};

std::ostream & operator<< (std::ostream & output, Circle const & print_me) {
  output << "A circle at (" << print_me.x << ", " << print_me.y << ") with radius " << print_me.radius << ".";
}

int main (void) {
  Circle my_circle;
  my_circle.x = 5;
  my_circle.y = 10;
  my_circle.radius = 20;

  std::cout << my_circle << '\n';

  return 0;
}
+4

Operators can be thought of as functions with syntactic sugar that allow pure syntax. This is just a case of operator overloading.

+1
source

Source: https://habr.com/ru/post/1537771/


All Articles