//代码测试 运行环境vc++2010#include <iostream>#include <fstream>#include <string>using namespace std;class ClsCopyfile{public : ClsCopyfile(char * sfile="",char * dfile=""); ifstream & funGetInFile(); ofstream & funGetOutFile(); friend istream & operator>>(istream & stream,ClsCopyfile & copys) { string name; cout<<"请输入源文件名称(可加路径):"<<endl; stream.getline(copys.m_strSource_file,256); cout<<"请输入目标文件名称(可加路径):"<<endl; stream.getline(copys.m_strDect_file,256); return stream; } int funCopyFile();private: char m_strSource_file[256]; char m_strDect_file[256]; char buff[4096];};ClsCopyfile::ClsCopyfile(char sfile[256],char dfile[256]){ strcpy(m_strSource_file,sfile); strcpy(m_strDect_file,dfile);}ifstream & ClsCopyfile::funGetInFile(){ //new 返回是一内存地址. 如果不用new 则不能使用局部变量当作引用 ifstream & in_file=*(new ifstream(m_strSource_file,ios::in|ios::binary));//两个流对象同时采用二进制方式 return in_file;}ofstream & ClsCopyfile::funGetOutFile(){//也可以用静态局部变量 static ofstream copy_file(m_strDect_file,ios::binary|ios::trunc|ios::out); ofstream ©_file=*(new ofstream(m_strDect_file,ios::binary|ios::trunc|ios::out)); // 若加ios::trunc//与文件创建链接,如果文件不存在,则创建文件,文件存在,先删除原文件再创建 return copy_file;}int ClsCopyfile::funCopyFile(){ ifstream &in=funGetInFile();//如果不使用 &in会报错,在vs2008以后 从“类”创建的对象无法访问该“类”的 protected 或 private 成员,不可以执行拷贝构造函数 if(!in) { cout<<"文件不存在!"<<endl; return 0; } else { ofstream &out=funGetOutFile(); if(!out) { cout<<"复制数据失败!"<<endl; return 0; } else { int n=0; while(!in.eof())//没有到文件末尾 { in.read(buff,4096); n=int(in.gcount());//实际读取数 out.write(buff,n); } out.close(); } } in.close(); return 1; }int main(){ ClsCopyfile copy; cin>>copy; if(copy.funCopyFile()) { cout<<"数据复制成功!"<<endl; } return 0;}//new 是动态分配堆内存,返回的是指针(内存地址),在程序退出之前,不用delete释放内存,则不会自动释放,程序结束自动释放。