C++中关于将fstream对象作为函数参数传递相关问题说明

Xiaohui Huang, [email protected]
China University of Geosciences, Wuhan , 430074
School of Computer. Network Engineering


一、问题说明

最近手上的一段代码大致要求是要将fstream对象作为函数参数进行传递。大致代码如下:

#include
#include

using namespace std;

class A
{
	public:
		void Func(fstream a);	
};

void A::Func(fstream s)
{
	//将一段字符串输入到fstream对象所关联的文件中 
	s<<"This is a Testing Program."<Func(word);
	return 0;
}

但是这段代码编译时有错误。在上网查阅相关资料后,将原始代码改成如下,代码成功运行:
#include
#include

using namespace std;

class A
{
	public:
		void Func(fstream &a);	
};

void A::Func(fstream &s)
{
	//将一段字符串输入到fstream对象所关联的文件中 
	s<<"This is a Testing Program."<Func(word);
	return 0;
}

最后,打开newtext.txt,截图如下:

C++中关于将fstream对象作为函数参数传递相关问题说明_第1张图片


二、问题相关说明

在将文件流对象作为参数进行传递时,一般是利用引用,即:

void Func(fstream &a){ }//编译成功


That is all.



你可能感兴趣的:(C++)