输入和输出重载操作符

从Vec2类的输入输出流重载说起:一份C++ IO流操作符(<<和>>)的避坑指南 本文深入探讨了C++中Vec2类的流操作符重载(<<和>>)的常见陷阱与解决方案。通过分析流状态管理、输入格式错误处理、输出格式控制等关键点,提供了一份实用的避坑指南,帮助开发者构建健壮的IO流操作符实现,特别适用于图形处理和物理引擎开发中的二维向量操作。 阅读详情

类的设计如下:

class sales_item
{
public:
	friend istream& operator>>(istream&, sales_item&);
	friend ostream& operator<<(ostream&, const sales_item&);

	//explicit sales_item(void); // 防止隐式转换
	sales_item(void) /*const*/;  //构造函数不能声明为const,默认构造函数
	~sales_item(void);

	sales_item(istream &is);//形参为输入流的构造函数
	sales_item(const string & book ); //const可以避免形参被修改,引用可以避免复制实参
	sales_item(const sales_item &org); //复制构造函数
	
	//int operator+(int, int); //error 不能对已有的操作符进行重定义
	//sales_item operator**(const sales_item &org); //error 不能通过连接其他合法操作符来创建任何新的操作符	
	//sales_item operator+(const int a, const int b); //error 必须至少提供一个类类型
	//sales_item operator+( const int b = 0 ); //error 不能有默认实参
	//sales_item operator+( const int b ); // ok 默认this为类类型
	sales_item& operator=( const sales_item& );//赋值操作符
	ostream& operator<<( ostream& );  //这个返回值一定是流,会在判断条件中判断流的状态

	string GetISBN() const { return isbn; }
	int GetUnitsSold() const { return units_sold; }
	double GetRevenue() const { return revenue; }
	inline double avg_price() const; //这里声明为inline,定义处不必再声明
	bool same_ishn(const sales_item & rhs) const;	
	
private:
	string isbn;
	int units_sold;
	double revenue;
};
//非成员函数重载运算符
istream& operator>>(istream&, sales_item&); //输入
ostream& operator<<(ostream&, const sales_item&); //输出

注意这里一定要按照上节的要求设计重载操作符,这里设计为非类成员,因为设计为类成员的话,如下函数

//调用的时候,只能使用classObject << cout;
ostream& sales_item::operator<<(ostream& os)
{
	os << isbn;
	return os;
}
调用的时候必须是obj<<cout,这与我们默认使用方式不一样的,因为第一个形参已经默认为this
非类成员的输入输出重载操作符的实现

//操作符 >>
istream& operator>>(istream& is, sales_item& s)
{
	double price;
	is >> s.isbn >> s.units_sold >> price;
	if (is)
	{
		s.revenue = s.units_sold*price;
	}
	else
	{
		s = sales_item();
	}
	return is;
}

//操作符 <<
ostream& operator<<(ostream& os, const sales_item& s)
{
	//先调用库函数提供的<<,全部重定向到os流中
	os <<"ISBN\t" << "SoldNum\t" << "Revenue\t" << "AveragePrice" << endl;
	os << s.isbn << "\t" << s.units_sold << "\t" << s.revenue << "\t" << s.avg_price();
	return os;
}

这里看输出操作符,使用了两个形参,第一个为流就可以保证输出的时候cout<<obj,这里注意定义为非成员函数,一定要将这两个函数设为类的友元函数,否则无法访问类内有些成员变量或者函数。

调用测试:

	const string book = "1-23-45678";
	sales_item sales0;
	sales_item sales1("hello world");  
	sales_item sales2 = sales_item(); //定义

	sales1 << cout << endl; //类成员重载操作符
	cout << sales1 << endl; //非类成员重载操作符
#if 1
	if (!sales1.same_ishn(sales2))
	{
#if 0
		cout << sales1 + sales2 << endl;
#else
		cout << sales1.operator+(sales2) << endl;
#endif
	}
#endif
	
	cin >> sales0;
	cout << sales0 << endl;

这里我们测试用例里面还有成员输出的测试,另外就是这里使用了+,必须定义了,否则cout无法输出+后的结果

C++重载输入和输出操作符以及IO标准库中的刷新输入缓冲区残留字符问题 今天在做C++ Primer习题的14.11时,印象中应该挺简单的一题,结果却费了很长时间。 类定义: typedef string Date; class CheckoutRecord{ public: CheckoutRecord(){book_id=-1;} friend ostream& operator<<(ostream &os,const CheckoutRecord 阅读详情

相关推荐

opencv图像去畸变

opencv图像去畸变

智能机器人产学研基地 4878

输入输出运算符的重载

运算符重载相信大家都不陌生。运算符函数通常分为两种形式:一类是在类中定义的运算符成员函数,称之为类成员运算符;另一种在类之外定义的运算符重载,通常以该类的友元形式,称之为友元运算符。 1、重载输入输出运算符的形式。常见的形式如下: 类型中声明友元函数(友元函数必须在类中声明) class Complex{ public: Complex( double r=0,...

mijichui2153的博客 1万+

基于springboot生鲜食品订购系统的设计与实现

近年来互联网络的迅猛发展和电子终端设备的普及,赋予了各行业充足的发展空间。微信小程序的O2O生鲜食品订购相比于传统信息技术,时效性是它最大的特色,已经在电子娱乐、经济等中发挥着举足轻重的作用。短时间内迅速扩大了线上管理系统的规模。尽管O2O生鲜食品订购已经有了很大程度的发展,但在微信小程序的O2O生鲜食品订购领域上却少有建设。

1025

[C++学习笔记]C++ 友元 和 内部类

C++ 友元类和内部类的简单的知识整理

weixin_51654781的博客 712

告别仿真报错!手把手教你为Intel MAX10 FPGA定制IBIS模型(附Allegro Skill工具)

本文详细介绍了为Intel MAX10 FPGA定制IBIS模型的完整流程,解决信号完整性仿真中的管脚映射问题。通过Allegro Skill工具自动化处理管脚信息,优化IBIS模型关键段落,提升仿真效率和精度,适用于高速数字电路设计。

weixin_33217202的博客 326

用Matlab系统辨识工具箱搞定温控系统建模:从阶跃响应到传递函数(附完整代码)

本文详细介绍了如何使用Matlab系统辨识工具箱进行温控系统建模,从阶跃响应数据采集到传递函数参数辨识的全过程。通过实际案例和完整代码,帮助工程师快速掌握PID控制参数整定技巧,提升温控系统设计效率。特别适合单片机开发者和自动化控制工程师参考。

weixin_30736301的博客 311

[C++系列] 28. friend友元

友元分为:友元函数和友元类 友元提供了一种突破封装的方式,有时提供了便利。但是友元会增加耦合度(相互之间的联系,高内聚、低耦合。即把强相关的东西打包在一起,把不相关的东西令其各自不要产生影响)其破坏了封装,所以友元不宜多用。 1.友元函数 问题:现在我们尝试去重载operator<<,然后发现我们没办法将operator<<重载成成员函数。因为cout的输出流对象和隐含...

Y-puyu 的博客 682

手把手教你为ArduPilot添加自定义飞行模式:以自动巡检航线为例

本文详细介绍了如何为开源飞控ArduPilot添加自定义飞行模式,并以自动巡检航线为例,提供了从状态机设计、代码实现到地面站集成的完整开发指南。通过七步法手把手教学,帮助开发者深入理解飞控核心逻辑,实现无人机自主执行复杂巡检任务,满足行业应用定制需求。

weixin_29306875的博客 139

c++输入输出流运算符的重载

说明:输入输出运算符的重载必须为友元函数,并且必须有输入输出流的返回值,固定格式为: friend istream& operator >> (istream&, 重载类名&); friend ostream& operator << (ostream&,重载类名&); 测试代码: #include<io...

lord12580的博客 5709

勇闯dify v1.0.0之设置模型供应商。解决:Reached maximum retries (3) for URL https://marketplace.dify.ai/

朋友们,大家好,今天带大家来勇闯dify v1.0.0。为什么叫勇闯呢?我就这么说吧,本来我昨天就想带大家勇闯v1.0.0的。但是dify的marketplace访问不了。公司的网和手机热点都试了,就是访问不了。我们连个模型都没有,还勇闯个球啊,对吧,就搁置了。今天,我赶紧看看这个marketplace好了没。一看,可以了。赶紧写下这篇博客,帮助同志们走出困境。

xiezhipu的博客 4617

手把手教你学Simulink--H桥逆变器的PWM控制设计与仿真

本文详细介绍了如何在Simulink环境中设计和仿真一个基于PWM控制的H桥逆变器。H桥逆变器广泛应用于电机驱动、UPS和可再生能源系统等领域,通过PWM技术可以有效控制输出电压的幅度和频率,减少谐波失真,提高系统效率和稳定性。文章首先介绍了所需的工具和环境,包括MATLAB/Simulink和SimscapeElectrical工具箱。接着,详细阐述了从定义任务需求、创建Simulink项目、建立基础电气模型、集成传感器模型、实现PWM控制算法到设置仿真参数和运行仿真的完整步骤。最后,文章总结了通过Sim

MHD0815的博客 721

C++中操作符<<重载

在 C++ 中,

zhangdaolong 1121

RK3588开发笔记-麦克风阵列多pdm通道合并成一个声卡

在音频设备的开发中,特别是在多通道音频数据处理场景中,如何将多个PDM(Pulse Density Modulation)通道整合成一个声卡设备,是一个非常具有挑战性的问题。RK3588芯片作为一款性能强大的平台,提供了对多个音频通道的支持。本文将介绍如何在RK3588上将多个PDM通道合并成一个麦克风阵列声卡,从而在Linux系统下统一管理和使用,提高多通道音频的同步性。在本文中我们主要介绍使用2通道回采+4通道mic声音采集构成一个6通道声卡,加以回声消除实现一个多麦克风阵列。

flypig has a dream! 1927

【C++重载操作符与转换】输入和输出操作符

在 C++ 编程中,操作符重载是一项强大的特性,它允许我们为自定义数据类型赋予运算符新的含义,使其能像内置类型一样自然地参与各种操作。输入(>>)和输出(<<)操作符作为与用户交互的重要接口,对它们进行合理重载能极大提升自定义类型的易用性和可读性。

byte轻骑兵的技术小窝 1252

LinePhone3.2.7(android端最新版本) sip客户端

SIP客户端For android:LinePhone3.2.7(最新版本),官网地址:http://www.linphone.org/

数学建模模型总结

这是本人在两年内准备参加数学建模竞赛搜集到的模型资料,已经经过了本人的筛选和整理,希望能够对准备参加数学建模竞赛的学弟学妹们提供一些帮助!

输入和输出的操作符重载

  看了一下c++primer 发现自己对c++操作符重载的一些细节问题以前没有弄清楚的,现在都基本明白了/* * ===================================================================================== * * Filename: x.cpp * * Description: c++输入输出操作符重载 * * Version: 1.0 * C

wyx819的专栏 373

深度学习工具包 DeepLearningToolbox

深度学习工具包Deprecation notice.-----This toolbox is outdated and no longer maintained.There are much better tools available for deep learning than this toolbox, e.g. [Theano](http://deeplearning.net/software/theano/), [torch](http://torch.ch/) or [tensorflow](http://www.tensorflow.org/)I would suggest you use one of the tools mentioned above rather than use this toolbox.Best, Rasmus.DeepLearnToolbox================A Matlab toolbox for Deep Learning.Deep Learning is a new subfield of machine learning that focuses on learning deep hierarchical models of data.It is inspired by the human brain's apparent deep (layered, hierarchical) architecture.A good overview of the theory of Deep Learning theory is[Learning Deep Architectures for AI](http://www.iro.umontreal.ca/~bengioy/papers/ftml_book.pdf)For a more informal introduction, see the following videos by Geoffrey Hinton and Andrew Ng.* [The Next Generation of Neural Networks](http://www.youtube.com/watch?v=AyzOUbkUf3M) (Hinton, 2007)* [Recent Developments in Deep Learning](http://www.youtube.com/watch?v=VdIURAu1-aU) (Hinton, 2010)* [Unsupervised Feature Learning and Deep Learning](http://www.youtube.com/watch?v=ZmNOAtZIgIk) (Ng, 2011)If you use this toolbox in your research please cite [Prediction as a candidate for learning deep hierarchical models of data](http://www2.imm.dtu.dk/pubdb/views/publication_details.php?id=6284)```@MASTERSTHESIS\{IMM2012-06284, author = "R. B. Palm", title = "Prediction as a candidate for learning deep hierarchical models of data", year = "2012",}```Contact: rasmusbergpalm at gmail dot comDirectories included in the toolbox-----------------------------------`NN/` - A library for Feedforward Backpropagation Neural Networks`CNN/` - A library for Convolutional Neural Networks`DBN/` - A library for Deep Belief Networks`SAE/` - A library for Stacked Auto-Encoders`CAE/` - A library for Convolutional Auto-Encoders`util/` - Utility functions used by the libraries`data/` - Data used by the examples`tests/` - unit tests to verify toolbox is workingFor references on each library check REFS.mdSetup-----1. Download.2. addpath(genpath('DeepLearnToolbox'));Example: Deep Belief Network---------------------```matlabfunction test_example_DBNload mnist_uint8;train_x = double(train_x) / 255;test_x = double(test_x) / 255;train_y = double(train_y);test_y = double(test_y);%% ex1 train a 100 hidden unit RBM and visualize its weightsrand('state',0)dbn.sizes = [100];opts.numepochs = 1;opts.batchsize = 100;opts.momentum = 0;opts.alpha = 1;dbn = dbnsetup(dbn, train_x, opts);dbn = dbntrain(dbn, train_x, opts);figure; visualize(dbn.rbm{1}.W'); % Visualize the RBM weights%% ex2 train a 100-100 hidden unit DBN and use its weights to initialize a NNrand('state',0)%train dbndbn.sizes = [100 100];opts.numepochs = 1;opts.batchsize = 100;opts.momentum = 0;opts.alpha = 1;dbn = dbnsetup(dbn, train_x, opts);dbn = dbntrain(dbn, train_x, opts);%unfold dbn to nnnn = dbnunfoldtonn(dbn, 10);nn.activation_function = 'sigm';%train nnopts.numepochs = 1;opts.batchsize = 100;nn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.10, 'Too big error');```Example: Stacked Auto-Encoders---------------------```matlabfunction test_example_SAEload mnist_uint8;train_x = double(train_x)/255;test_x = double(test_x)/255;train_y = double(train_y);test_y = double(test_y);%% ex1 train a 100 hidden unit SDAE and use it to initialize a FFNN% Setup and train a stacked denoising autoencoder (SDAE)rand('state',0)sae = saesetup([784 100]);sae.ae{1}.activation_function = 'sigm';sae.ae{1}.learningRate = 1;sae.ae{1}.inputZeroMaskedFraction = 0.5;opts.numepochs = 1;opts.batchsize = 100;sae = saetrain(sae, train_x, opts);visualize(sae.ae{1}.W{1}(:,2:end)')% Use the SDAE to initialize a FFNNnn = nnsetup([784 100 10]);nn.activation_function = 'sigm';nn.learningRate = 1;nn.W{1} = sae.ae{1}.W{1};% Train the FFNNopts.numepochs = 1;opts.batchsize = 100;nn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.16, 'Too big error');```Example: Convolutional Neural Nets---------------------```matlabfunction test_example_CNNload mnist_uint8;train_x = double(reshape(train_x',28,28,60000))/255;test_x = double(reshape(test_x',28,28,10000))/255;train_y = double(train_y');test_y = double(test_y');%% ex1 Train a 6c-2s-12c-2s Convolutional neural network %will run 1 epoch in about 200 second and get around 11% error. %With 100 epochs you'll get around 1.2% errorrand('state',0)cnn.layers = { struct('type', 'i') %input layer struct('type', 'c', 'outputmaps', 6, 'kernelsize', 5) %convolution layer struct('type', 's', 'scale', 2) %sub sampling layer struct('type', 'c', 'outputmaps', 12, 'kernelsize', 5) %convolution layer struct('type', 's', 'scale', 2) %subsampling layer};cnn = cnnsetup(cnn, train_x, train_y);opts.alpha = 1;opts.batchsize = 50;opts.numepochs = 1;cnn = cnntrain(cnn, train_x, train_y, opts);[er, bad] = cnntest(cnn, test_x, test_y);%plot mean squared errorfigure; plot(cnn.rL);assert(er<0.12, 'Too big error');```Example: Neural Networks---------------------```matlabfunction test_example_NNload mnist_uint8;train_x = double(train_x) / 255;test_x = double(test_x) / 255;train_y = double(train_y);test_y = double(test_y);% normalize[train_x, mu, sigma] = zscore(train_x);test_x = normalize(test_x, mu, sigma);%% ex1 vanilla neural netrand('state',0)nn = nnsetup([784 100 10]);opts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samples[nn, L] = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.08, 'Too big error');%% ex2 neural net with L2 weight decayrand('state',0)nn = nnsetup([784 100 10]);nn.weightPenaltyL2 = 1e-4; % L2 weight decayopts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex3 neural net with dropoutrand('state',0)nn = nnsetup([784 100 10]);nn.dropoutFraction = 0.5; % Dropout fraction opts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex4 neural net with sigmoid activation functionrand('state',0)nn = nnsetup([784 100 10]);nn.activation_function = 'sigm'; % Sigmoid activation functionnn.learningRate = 1; % Sigm require a lower learning rateopts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex5 plotting functionalityrand('state',0)nn = nnsetup([784 20 10]);opts.numepochs = 5; % Number of full sweeps through datann.output = 'softmax'; % use softmax outputopts.batchsize = 1000; % Take a mean gradient step over this many samplesopts.plot = 1; % enable plottingnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex6 neural net with sigmoid activation and plotting of validation and training error% split training data into training and validation datavx = train_x(1:10000,:);tx = train_x(10001:end,:);vy = train_y(1:10000,:);ty = train_y(10001:end,:);rand('state',0)nn = nnsetup([784 20 10]); nn.output = 'softmax'; % use softmax outputopts.numepochs = 5; % Number of full sweeps through dataopts.batchsize = 1000; % Take a mean gradient step over this many samplesopts.plot = 1; % enable plottingnn = nntrain(nn, tx, ty, opts, vx, vy); % nntrain takes validation set as last two arguments (optionally)[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');```[![Bitdeli Badge](https://d2weczhvl823v0.cloudfront.net/rasmusbergpalm/deeplearntoolbox/trend.png)](https://bitdeli.com/free "Bitdeli Badge")

c++输入和输出操作符重载

#include #include using namespace std; class Person{ private: string name; int age; public: Person(string n,int a):name(n),age(a){} friend ostream& operator<<(ostream&,const Person&); }; //ios操作

h9911的专栏 398

jre9下载 jdk9

(Java SE Runtime Environment 9.0) 9.0u175 官方最新版 【x86|x64】

运算符重载之——输入和输出操作符

一:输出操作符 #include using namespace std; class String { friend ostream& operator<<(ostream& os,const ClassType &object); os<<object; return os; } 第一个形参是对 ostream 对象的引用,在该对象上将产生输出。ostream 为非 c

D-Boy的专栏 1045

C++----重载<<输出操作符和>>输入操作符

在实现之我们要先了解 cout是一个对象,该对象的类型是ostream,该类包含在头文件<iostream>中,cout是<iostream>中定义的一个全局对象。这时我们就不能把操作符的重载写成成员函数,因为成员函数一定会有隐藏的this指针,所以这里重载操作符就不能使用成员函数重载,要重载成全局函数。这里之所以要d1<<cout才能运行,是因为,这里的运算符重载函数是有两个参数的,其中左边有一个隐藏的this指针。首先我们先写一个简单的日期类,然后试着在Date类中重载一个输出操作符的成员函数。

2402_83149124的博客 424

C++学习基础八——重载输入和输出操作符

C++学习基础八——重载输入和输出操作符 一、重载输入操作符的要点: 1、返回值为istream &。 2、第一个参数为istream &in。 3、第二个参数为自定义类型的引用对象(例如Sales_Item &item)。 二、重载输出操作符的要点: 1、返回值为ostream &。 2、第一个参数...

weixin_30598225的博客 180

C++重载输入与输出操作符

C++重载输入与输出操作符C++重载输入与输出操作符stream friend C++重载输入与输出操作符 在 C++ 中,系统已经对左移操作符“<<”和右移操作符“>>”分别进行了重载,使其能够用作输入输出操作符,但是输入输出的处理对象只限于系统内建的数据类型。系统重载这两个操作符是以系统类成员函数的形式进行的,因此cout<< var; 语句可以理解为: cout.operator<<(var); 如果我们自己定义了一种新的数据类型,需要用输入输出操作符

嵌入式与人工智能 1218

C++ 操作符重载

输出操作符"<<" 和输入操作运算符">>" 在C++中,左移运算符<<可以和cout一起输出,因此也常被称为"流插入运算符",或"输出运算符"。 但实际上!<<本来没有这样的功能,之所以能和cout一起使用来输出数据,是因为此<<操作符被重载了 输出操作符"<<" cout是ostream类的对象,ostream类和cout都是在头文件 <iostream> 中声明的,ostream类将<<重载为其成员函数,

Chroniccandy的博客 2008

7.2流类通过重载哪些操作符执行输出和输入操作?它们又分别被称作什么?

流类通过重载运算符>执行输出和输入操作。在流操作中,将运算符>称为提取符

iwodgirl的专栏 600
上一篇: C++重载操作符
下一篇: 算法操作符和关系操作符
comwise
博客等级 码龄15年 58粉丝 85原创
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

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

抵扣说明:

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

余额充值