How can I overload << and >> bitwise operator in c++?

How can I overload << and >> bitwise operator in c++?
And what is the use of these operators after oveloading?
If you google 'operator overloading', you will likely find plentiful resources.

But to do it sensibly, you probably first need to have a few of your own user-defined types (structures and classes) on which those operators should operate.

The use of overloaded operators is whatever functionality you give them. You choose the new functionality.

The syntax of using overloaded operators and their priority stays the same as usual.



> How can I overload << and >> bitwise operator in c++?

Like any of the other binary arithmetic operators.


> what is the use of these operators after overloading?

What is its use, or whether it has any use at all, depends on context.

The primary (only) purpose of overloading an operator is enhanced readability
(program constructs have greater intuitive expressive power).

For instance, if we were implementing a shift cipher, this may be convenient:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
#include <iostream>
#include <string>
#include <algorithm>
#include <iomanip>

std::string operator<< ( std::string text, std::size_t n )
{
    if( !text.empty() ) std::rotate( text.begin(), text.begin() + n%text.size(), text.end() ) ;
    return text ;
}

std::string operator>> ( std::string text, std::size_t n )
{
    if( !text.empty() ) std::rotate( text.rbegin(), text.rbegin() + n%text.size(), text.rend() ) ;
    return text ;
}

int main()
{
    std::string alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZ" ;

    std::cout << std::quoted(alphabet) << '\n' // "ABCDEFGHIJKLMNOPQRSTUVWXYZ"

              << std::quoted( alphabet << 10 ) << '\n' // "KLMNOPQRSTUVWXYZABCDEFGHIJ"

              << std::quoted( alphabet >> 10 ) << '\n' ; // "QRSTUVWXYZABCDEFGHIJKLMNOP"
}

http://coliru.stacked-crooked.com/a/fdc1b139e5078ef3
The primary (only) purpose of overloading an operator is enhanced readability
(program constructs have greater intuitive expressive power).


I think that you are interpreting OP's question too literally. On the other hand, I can understand you.
Topic archived. No new replies allowed.