1. 创建操作算子
#include <iostream>
using namespace std;
ostream& nl (ostream& os )
{
return os<<"/n";
}
int main()
{
cout<<"new line"<<nl<<"between"<<nl<<"new"<<nl<<"line"<<nl;
}
2. 创建效用算子
#include <cassert>
#include <limits>
#include <sstream>
#include <string>
using namespace std;
class Fixw
{
string str;
public:
Fixw (const string& s, int width) : str (s,0,width) {}
friend ostream& operator<<(ostream& os, const Fixw& fx)
{
return os<<fx.str;
}
};
typedef unsigned long ulong;
class Bin
{
ulong ul;
public:
Bin (ulong nn) {ul = nn;}
friend ostream& operator<<(ostream& os, const Bin& b)
{
const ulong ULMAX = numeric_limits<ulong>::max();
ulong bit = -(ULMAX >> 1);
while(bit)
{
os<<(b.ul & bit ? '1':'0');
bit >>= 1;
}
return os;
}
};
int main()
{
string words = "Things that make us happy, make us wise.";
for(int i = words.size(); -- i>= 0;)
{
ostringstream s;
s << Fixw(words, i);
assert(s.str() == words.substr(0, i));
}
ostringstream xs, ys;
xs << Bin(0xCAFEBABEBEUL);
assert(xs.str() == "1100""1010""1111""1110""1011""1010""1011""1110");
ys << Bin(0x76543210UL);
assert(ys.str() == "0111""0110""0101""0100""0011""0010""0001""0000");
}