此篇博客提供最简单的例子,便于学习基本用法,所有代码均可以使用我的makefile博客中的第四版makefile编译
文件操作
打开一个文件,写入123再读出来。
#include <iostream>
#include <fstream>
using namespace std;
int main()
{
char data[10];
ofstream openfile( "myfile.txt" );
openfile << 123 << endl;
openfile.close();
//写入部分
ifstream infile( "myfile.txt" );
infile >> data;
cout << data << endl;
infile.close();
//读取部分
return(0);
}
new和delete
#include <iostream>
using namespace std;
int main ()
{
int* pvalue = NULL; // 初始化为 null 的指针
pvalue = new int; // 为变量请求内存
*pvalue = 123; // 在分配的地址存储值
cout << *pvalue << endl;
delete pvalue; // 释放内存
return 0;
}
函数模板
#include <iostream>
using namespace std;
template <class T>
T min(T x,T y)
{
return(x<y)?x:y;
}
int main( )
{
int n1=2,n2=10;
double d1=1.5,d2=5.6;
cout<< "较小整数:"<<min(n1,n2)<<endl;
cout<< "较小实数:"<<min(d1,d2)<<endl;
return 0;
}
注意不要用min当函数名,因为min函数在std中已存在。