//自定义输出操作符函数的应用。
#include <iomanip>
#include<iostream>
using namespace std;
ostream& sethex(ostream& a)
{
//1a.setf(ios::uppercase);
a<<setw(2)<<uppercase<<hex; //域宽 大写
return a;
}
int main()
{
int n;
cout<<"Please Input Integer n=";
cin>>n;
cout<<"系统默认十进制格式输出:";
cout<<"n="<<showpos<<n<<endl; //符号
cout<<"自定义十六进制格式输出:";
cout<<sethex<<"n="<<n<<endl;
}
//类内运算符重载
#include<iostream>
using namespace std;
class Vector
{
private:
int x;
int y;
public:
Vector(int a=0,int b=0):x(a),y(b){}
Vector operator + (Vector &a)
{
Vector c;
c.x=x+a.x;
c.y=y+a.y;
return c;
}
friend ostream & operator << (ostream &o,Vector &c);
};
ostream & operator << (ostream &o,Vector &c)
{
o<<'<'<<c.x<<','<<c.y<<'>';
return 0;
}
int main(void)
{
Vector a(5,9),b(7,8);
Vector c;
c=a+b;
cout<<a<<b<<c<<endl;
}
#include<iostream>
using namespace std;
class Vector
{
private:
int x,y;
public:
Vector(int a=0,int b=0):x(a),y(b){}
friend Vector operator + (Vector &a, Vector &b);
friend ostream & operator << (ostream &a,Vector &c);
};
Vector operator + (Vector &a, Vector &b)
{
Vector c;
c.x=a.x+b.x;
c.y=a.y+b.y;
return c;
}
ostream & operator << (ostream &a,Vector &c)
{
a<<"<"<<c.x<<","<<c.y<<">";
return a;
}
int main(void)
{
Vector a(1,2);
Vector b(3,4);
Vector c;
c=a+b;
cout<<a<<" "<<b<<" "<<c<<endl;
}
//用户自定义输入操作符函数。
#include <iomanip>
#include<iostream>
using namespace std;
istream& hexInput(istream& stream)
{
cin>>hex;
cout<<"Input hex number:";
return stream;
}
int main()
{
int a;
int b;
cin>>hexInput>>a;
cout<<a<<endl;
cin>>hexInput>>b;
cout<<b<<endl;
}
//文本文件格式的写操作举例
#include<iostream>
#include<iomanip>
#include<fstream>
#include<string.h>
using namespace std;
void testwrite()
{
ofstream outcth;
outcth.open("test10.txt");
if(!outcth)
{
cerr<<"Error!Cannot open file!";
exit(1);
}
char ch[]="this is C++ file!char is:";
int n,i,s1=0;
n=strlen(ch);
for(i=0;i<n;i++)
{
outcth.put(ch[i]);
cout<<ch[i];
}
}
int main(void)
{
testwrite();
}
//文本文件格式读操作举例。
#include<fstream>
#include<stdlib.h>
#include<iostream>
using namespace std;
void testread()
{ ifstream incth("test1.txt",ios::in);
//incth.open("test1.txt",ios::in);
if(!incth)
{ cerr<<"Error! Cannot open file!"<<endl;
exit(1); }
char ch; int total=0;
//将文件中的字符序列插入到内存变量
while(incth.get(ch)){
cout.put(ch);
total++; }
cout<<endl;
cout<<"the amount of char is:"<<total<<endl;
}
int main()
{ testread();
}