64,678
社区成员
发帖
与我相关
我的任务
分享
#include <iostream>
using namespace std;
class Byte
{
public:
Byte(const unsigned char c):ch_(c) {};
protected:
friend std::ostream& operator << (std::ostream& out,const Byte& b);
private:
unsigned char ch_;
};
std::ostream& operator << (std::ostream& out,const Byte& b)
{
for (int i = 7; i >= 0; i--)
{
if ( b.ch_ & (1 << i) )
out << '1';
else
out << '0';
}
return out;
}
template <typename T>
class MemoryMap ;
template <typename T>
std::ostream& operator << (std::ostream& out,MemoryMap <T>& x) ;
template <typename T>
class MemoryMap
{
public:
MemoryMap(const T& x):data_(x) {};
protected:
friend std::ostream& operator << (std::ostream& out, MemoryMap <T>& x)
{
size_t length=sizeof(x.data_);
Byte* p=reinterpret_cast <Byte*>(&x.data_);
for (size_t i=0;i <length;i++)
{
out <<*p++ <<' ';
if (i>4 && i%4==0 ) out <<'\n';
}
return out;
}
private:
T data_;
};
int main()
{
std::string s="\00a";
cout << s << endl;
MemoryMap <std::string> mm(s);
cout << mm <<endl;
return 0;
}
if (i>4 && i%4=0 ) out <<'\n';
#include <iostream>
using namespace std;
//
class Byte
{
public:
Byte(const unsigned char c):ch_(c) {};
protected:
friend std::ostream& operator << (std::ostream& out,const Byte& b);
private:
unsigned char ch_;
};
//
std::ostream& operator << (std::ostream& out,const Byte& b)
{
for (int i = 7; i >= 0; i--)
{
if ( b.ch_ & (1 << i) )
out << '1';
else
out << '0';
}
return out;
}
//
template <typename T>
class MemoryMap ;
template <typename T>
std::ostream& operator << (std::ostream& out,MemoryMap <T>& x) ;
template <typename T>
class MemoryMap
{
public:
MemoryMap(const T& x):data_(x) {};
protected:
friend std::ostream& operator << <T>(std::ostream& out, MemoryMap <T>& x);
private:
T data_;
};
//
template <typename T>
std::ostream& operator << (std::ostream& out,MemoryMap <T>& x)
{
T* ptr=&x.data_;
size_t length=sizeof(x.data_);
Byte* p=reinterpret_cast <Byte*>(ptr);
for (size_t i=0;i <length;i++)
{
out <<*p++ <<' ';
if (i>4 && (i%4==0) ) out <<'\n';
}
return out;
}
//
int main()
{std::string s="\00a";
cout << s << endl;
MemoryMap <std::string> mm(s);
cout << mm <<endl;
return 0;
}