C++:自定义操作符函数

//自定义输出操作符函数的应用。
#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();
}

 

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值