C++ 面向对象编程 C++流

本文详细介绍了 C++ 中的输入输出流概念及其使用方法,包括流的状态设置、科学计数法显示等,并通过具体实例展示了如何重载输入输出运算符以实现自定义类的对象输入输出。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >



                                           C++流  输入输出流

流的概念:

   C++  键盘输入到变量, 然后变量不断流向输出设备, 因此称为输入输出流

   setf()函数用来设置流状态标识的

   unsetf() 函数 是cout 的成员函数 用来解除当前设置的

#include<iostream>
using namespace std;
int main()
{
    double x = 1.0000234;
    double y = 1.2345678;
    cout<<"默认格式:"<<endl;
    cout<<"x = "<<x<<" y = "<<y<<endl;
    cout<<"科学计数法:"<<endl;
    cout.setf(ios::scientific);
    cout<<"x = "<<x<<" y = "<<y<<endl;
    cout<<"恢复默认格式:"<<endl;
    cout.unsetf(ios::scientific);
    cout<<"x = "<<x<<" y = "<<y<<endl;
   return 0 ;
}



重载输入输出流:

插入符号<< 的标准格式

friend ostream & operator  <<(ostream &stream, 类名 &类引用名)

{

函数体;

       return stream;

}

看类子:

#include<iostream>
using namespace std;
class myclass
{
    int x, y;
    public:
        myclass(int m , int n){x = m ; y = n;}
        friend ostream & operator <<(ostream & stream,myclass &s)
        {
            //这里面添加的是函数体
            cout<<"x = "<<s.x<<" y = "<<s.y<<endl;
            return stream;
        }
};
int main()
{
   myclass A(2, 3),b(23,14);
   cout<<A<<b<<endl;
}


提取运算符重载:

>> 称为是提取运算符, 对他进行重载的函数是提取符号函数

标准和格式:

friend istream & operator  >>(ostream &stream, 类名 &类引用名)

{

函数体;

       return stream;

}

 请看例子:

#include<iostream>
using namespace std;
class myclass
{
  int x , y;
  public:
    myclass(){}
    friend istream & operator>>(istream &stream, myclass &s)
    {
        //函数体
        cout<<"输入x 和y 的值:"<<endl;
        cout<<"x = ";
        cin>>s.x;
        cout<<"y = ";
        cin>>s.y;
        return stream;
    }
    //下面是输出x和y 的值
    friend ostream & operator <<(ostream &stream, myclass &s)
    {
        cout<<"输出x 和 y 的值:"<<endl;
         cout<<"x = "<<s.x<<" y = "<<s.y<<endl;
        return stream;
    }
};
int main()
{
    myclass a;
    cin>>a;
    cout<<a;
    return 0;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

wangxiaoming

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值