C++基础知识

重定向文件读入写入

#include<iostream>
using namespace std;
int main(){
	
	freopen("in.txt","r", stdin); //必须要先保存好
	int a, b;
	cin>>a>>b;
	cout<<a+b<<endl;
	freopen("out.txt","w", stdout); //可以不存在
	cout<<"this is a test!"<<endl;
	return 0;
} 
#include<iostream>
using namespace std;

int main(){
	freopen("input.txt","r",stdin);//打开input文件,表明为读入,所有scanf的内容都是从这里读的 
	freopen("out.txt","w",stdout);//打开out文件,表明为写入,所有printf之类的内容都写在里面了 
	char str[200];
	scanf("%s",str); 
	printf("%s\n",str);
	printf("__hello!");
	fclose(stdin); //关闭读入 
	fclose(stdout); //关闭写入 
	return 0;
}

函数模板

#include<iostream>
using namespace std;
template <class T>
T add(T x, T y){
	return x+y;
}
int main(){
	double a,b;
	int c,d;
	cin>>a>>b;
	cout<<add(a,b)<<endl;
	cin>>c>>d;
	cout<<add(c,d)<<endl;
	
	return 0;
} 

重载为成员函数

#include<iostream>
using namespace std;
class Point{
	int x,y;
	public:
		Point(){}
		Point(int i, int j){
			x = i;
			y = j;
		}
		void disp(){
			cout<<"("<<x<<","<<y<<")"<<endl;
		}
		Point operator + (Point &p){
			return Point(x+p.x, y+p.y);
		}
}; 
int main(){
	Point p1(3,4),p2(5,6),p3;
	p3=p1+p2;
	p3.disp();
	return 0;
}

重载为友元函数

#include<iostream>
using namespace std;
class Point{
	int x,y;
	public:
		Point(){}
		Point(int i, int j){
			x = i;
			y = j;
		}
		void disp(){
			cout<<"("<<x<<","<<y<<")"<<endl;
		}
		friend Point operator + (Point &p1, Point &p2){
			return Point(p1.x+p2.x, p1.y+p2.y);
		}
}; 
int main(){
	Point p1(3,4),p2(5,6),p3;
	p3=p1+p2;
	p3.disp();
	return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值