C++详解(3) 标准IO库:面向对象(IO流)的标准库

  • 基本使用
// 省略头文件

int main()
{
	std::cout << "cout是标准输入库ostream输入流对象"  << std::endl;
	// 文件头加入 using namespace std
	// 可以省略 命名空间std
	cout << "cout是标准输入库ostream输入流对象"  << endl;
	return 0;
}
  • IO对象不支持赋值
// 省略头文件

int main()
{
	std::ofstream out1 out2;  // 定义两个ofstream对象 out1 out2
	
	out1 = out2 // error IO对象不支持赋值
	return 0;
}
  • IO对象不支持复制
// 省略头文件
void print(ofstream of)  // 复制
{
	std::cout << "print(ofstream of)" << std::endl;
}

void print2(ofstream &of)  // 引用
{
	std::cout << "print2(ofstream &of)" << std::endl;
}

int main()
{
	std::ofstream out1 out2;  // 定义两个ofstream对象 out1 out2
	
	print(out1); // error  IO对象不支持复制(这里是形参拷贝)
	print(out2); // right

	vector<ofstream> vec;  //error 保存在容器中的对象必须可以复制
	vec.push_back(out1);  //error
	vec.push_back(out2);  //error
	
	return 0;
}
// 省略头文件
// unsing namespace std;

ofstream test(ofstream &of)
{
	cout << "ofstream test(ofstream &of)" << endl;
	return of
}

ofstream& test2(ofstream &of)
{
	cout << "ofstream& test2(ofstream &of)" << endl;
	return of
}

int main()
{	
	ofstream out1, out2;
	// ofstream test(ofstream &of)
	test(out1) //  error 函数返回值时需要复制 而IO标准对象不支持复制
	// ofstream& test2(ofstream &of)
	test2(out2) // right: ofstream test(ofstream &of)
	return 0;
}
  • 继承 基类->子类
    ostream、istream是父类
    ofstream、ostringstream、iostream、istringstream、ifstream是子类
    子类可以使用父类
    在这里插入图片描述
// 省略头文件
// unsing namespace std;

void foo(ostream &os)
{
	cout << "test ostream" << endl;
}

int main()
{
	// cout
	foo(cout);  // result: test ostream	
	// ofstream类型
	ofstream ofs;
	foo(ofs); // result: test ostream
	// ostringstream类型
	ostringstream oss;
	foo(oss); // result: test ostream
	return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值