overload
dark777
jeanzonta777 at yahoo.com.br
Thu Dec 14 22:47:15 UTC 2017
I know that this community is not from c ++, but for some time I
studied how to do overload of ostream operators in c ++ and I
even managed to get to this result, I got to this result in
another post done here but I did not understand the that it
returns this error below:
bin2.cxx:44:43: error: expected ‘,’ or ‘...’ before ‘(’ token
std::ostream& operator<<(std::ios_base& (__cdecl
*_Pfn)(std::ios_base&))
^
bin2.cxx: In member function ‘std::ostream&
BinStream::operator<<(std::ios_base&)’:
bin2.cxx:46:16: error: ‘_Pfn’ was not declared in this scope
return os <<_Pfn;
so that the output is the same as below:
127 em binario: 0001111111
127 em octal: 177
127 em binario: 0001111111
127 em hexadecimal: 7f
127 em decimal: 127
127 em binario: 0001111111
and not this:
127 em binario: 0001111111
127 em octal: 0001111111
127 em binario: 0001111111
127 em hexadecimal: 0001111111
127 em decimal: 0001111111
127 em binario: 0001111111
#include <ios> //ios_base
#include <sstream>
#include <climits> // CHAR_BIT
#include <iostream>
#include <algorithm> // reverse
struct BinStream
{
std::ostream& os;
BinStream(std::ostream& os) : os(os) {}
std::string binario(unsigned int n)
{
//converte numero para string de bits
std::stringstream bitsInReverse;
//int nBits = sizeof(n) * CHAR_BIT;
unsigned int nBits = sizeof(n)*2.5;
while (nBits-- > 0)
{
bitsInReverse << (n & 1);
n >>= 1;
}
std::string bits(bitsInReverse.str());
std::reverse(bits.begin(), bits.end());
return bits;
}
template<class T>
BinStream& operator<<(T&& value)
{
os << value;
return *this;
}
BinStream& operator<<(int value)
{
os << binario(value);
return *this;
}
std::ostream& operator<<(std::ios_base& (__cdecl
*_Pfn)(std::ios_base&))
{
return os << _Pfn;
}
};
struct Bin
{
friend BinStream operator<<(std::ostream& os, const Bin&
f);
} bin;
BinStream operator<<(std::ostream& os, const Bin& f)
{
return BinStream(os);
}
int main()
{
std::cout << "\n\t127 em binario: " << binario(127)
<< "\n\t127 em binario: " << bin << 127
<< "\n\t127 em octal: " << std::oct << 127
<< "\n\t127 em binario: " << bin << 127
<< "\n\t127 em hexadecimal: " << std::hex << 127
<< "\n\t127 em binario: " << bin << 127
<< "\n\t127 em decimal: " << std::dec << 127
<< "\n\t127 em binario: " << bin << 127 << "\n\n";
}
More information about the Digitalmars-d-learn
mailing list