zoukankan      html  css  js  c++  java
  • c++学习记录(十三)

    流插入运算符和流提取运算符的重载

    • cout 是在iostream中定义的,是ostream类的对象,ostream包含在iostream头文件里
    • <<是左移运算符,能用在cout上是因为在iostream中对<<进行了重载
    • 有可能按以下方式重载成ostream类的成员函数
    void ostream::operator<<(int n)
    {
        ...//输出n的代码
        return;
    }
    
    • cout<<5cout.operator<<(5)
    • cout<<"this"同理
    • 但由于返回值是void不能实现cout<<5<<"this"

    - 那么怎么重载使得cout<<5<<"this"成立?

    • 希望返回值还是cout则可以连续
    • 已知coutostream类的对象
    ostream & ostream::operator<<(int n)
    {
        ...//
        return *this;
    }
    
    • cout<<5<<"this"本质上的函数调用形式为cout.operator<<(5).operator<<("this");

    - 示例

    • 要程序输出5hello
    class CStudent{
        public:int nAge;
    };
    int main(){
        CStudent s;
        s.nAge=5;
        cout<<s<<"hello";
        return 0;
    }
    ostream & operator<<(ostream & o,const CStudent & s)
    {
        o<<s.nAge;
        return 0;
    }
    
    • cinistream的对象
    • coutostream的对象

    类型转换运算符和自增、自减运算符的重载

    - 重载类型转换运算符

    • 每一个类型名其实就是类型转换运算符
    #include<iostream>
    using namespace std;
    class Complex
    {
        double real,imag;
        public:
            Complex (double r=0,double i=0):real(r),imag(i){};
            operator double(){
                return real;
             }//重载强制类型转换运算符
    };
    int main()
    {
        Complex c(1.2,3.4);
        cout<<(double)c<<endl;//输出1.2
        double n=2+c;//等价于double n=2+c.operator double()
        cout<<n;//输出3.2
    }
    
    • 重载类型转换运算符时返回值不写,因为类型就是它本身,double返回值类型就是double,没必要写

    - 自增、自减运算符的重载

    • 自增运算符++,自减运算符--有前置后置之分
    • 为了区分所重载的是前置运算符函数后置运算符,c++规定
      • 前置运算符作为一元运算符重载
        • 重载为成员函数
              T&operator++();
              T&operator--();
          
        • 重载为全局函数
              T1&operator++(T2);
              T1&operator--(T2);
          
      • 后置运算符作为二元运算符重载,多写一个没用的参数
        • 重载为成员函数
              T operator++(int);
              T operator--(int);
          
        • 重载为全局函数
              T1 operator++(T2,int);
              T1 operator--(T2,int);
          
    • 注意:在没用后置运算符重载而有前置运算符重载的情况下,在vs中obj++也调用前置重载,而dev则令obj++编译出错
    • ++a的返回值类型是a的引用,而a++的返回值是一个临时变量,是a+1之前的值,所以重载时前置和后置的返回值类型不一样

    - 运算符重载的注意事项

    • c++不允许定义新的运算符
    • 重载后的运算符含义应符合日常习惯
    • 运算符重载不改变运算的优先级
    • 一下运算符不能被重载..*::?:、sizeof
    • 重载运算符()[]->或者赋值运算符=时,运算符重载函数必须声明为类的成员函数

    至此函数的重载内容结束!

  • 相关阅读:
    使用Git遇到的问题及解决方案(初级)
    巧记前端易混淆的英文语法
    编程助手JavaScript学习库-DOM笔记
    编程助手JavaScript学习库-面向对象编程笔记
    JS原始类型:数值的运用技巧
    这题目有毒之干不过codewars的OJ系统(一)
    Javascript运算符进阶指南
    Qt:During startup program exited with code 0xc0000135
    QT 消息处理机制
    Windows环境 和 Linux环境下搭建Qt开发环境
  • 原文地址:https://www.cnblogs.com/2002ljy/p/12287352.html
Copyright © 2011-2022 走看看