operator overload
Biotronic
simen.kjaras at gmail.com
Tue Dec 12 16:54:17 UTC 2017
On Tuesday, 12 December 2017 at 15:52:09 UTC, dark777 wrote:
> I know that this community is not of c ++, but some time I have
> been studying how to do overload of ostream operators in c ++
> and I even managed to get to this result but the same is not
> converting to binary only presents zeros as output to any
> number already tried to pass parameter of variable and yet he
> is not getting the number for conversion how to solve it so
> that it works correctly?
>
> PS: if I use the same conversion algorithm in a function it
> converts normally it is not only converting to the output of
> the operator ..
>
>
> https://pastebin.com/BXGXiiRk
This line:
<< "\n\t127 em binario: " << bin << 127 << "\n\n";
Your hope is that the '<< bin' part should behave just like
std::hex does, except binary instead of hex. Right?
I'm afraid that's not how C++ formatting works. You can see a
hint of what happens in the output you get:
127 em binario: 000000000000127
The zeroes are from the uninitialized int in your Bin struct, and
the '127' is from the 127 you pass right after passing bin.
Translating to code that does not use operators, the behavior you
expect is something like this:
std::cout.print("\n\t127 em binario: ");
std::cout.setFormat(bin);
std::cout.print(127); // Should use bin for formatting
std::cout.print("\n\n");
The actual behavior is something like this:
std ::cout.print("\n\t127 em binario: ");
std::cout.print(bin); // Prints the value stored in bin. That
is, 0.
std::cout.print(127); // Prints 127 just the way it would
otherwise print it.
std::cout.print("\n\n");
There is no way in C++ to set the format the way you want it. If
you want binary output, you need to call a function like your
binario function.
The point of overloading operator<<(std::ostream&, MyType) is not
to format another type, but to be able to print MyType in a given
way. Basically like toString() in D, C# or Java.
--
Biotronic
More information about the Digitalmars-d-learn
mailing list