zoukankan      html  css  js  c++  java
  • 运算符重载(二)

        String类:

    一 []运算符的重载

        []运算符的使用可能有以下几种情况:

    String s1="asdfdsf";
    const String s2="abcd";
    
    char A=s1[2]; //1
    s1[2]='a'; //2
    
    char B=s2[2];  //3
    s2[2]='b';  //4

    对于1和2的情况,需要重载:

    char& operator[](unsigned int index);

    返回引用是为了可以实现情况2。

        对于const String,3允许但4不允许,所以要返回const string&

    char& String::operator[](unsigned int index)
    {
        //return str_[index];
        //non const 版本调用 const版本
        return const_cast<char&>(static_cast<const String&>(*this)[index]);//先把*this转换成从const,调用const函数,在去掉const属性
    }
    const char& String::operator[](unsigned int index) const
    {
        return str_[index];
    }

    二 +运算符的重载

    String s3 = "xxx";
    String s4 = "yyy";
    
    String s5 = s3 + s4; //1
    String s6 = "zzz" + s4;  //2

        为了允许情况2,+运算符需要重载为友元,同时还要有一个转换构造函数配合:

    friend oprator+(const String& s1, const String& s2);

     但是不允许+两侧都是非对象类型。

    String String::(const String& s1, cosnt String& s2)
    {
        int len = strlen(s1.str_) + strlen(s2.str_) + 1;
        char* newstr = new char[len];
        memset(newstr, 0, len);
        strcpy(newstr, s1.str_);
        strcat(newstr, s2.str_);
    
        String tmp(newstr);
        delete newstr;
        return tmp;
    }

    三 <<运算符

    friend ostream& operator<<(ostream& os, cosnt String& s);

     四 类型转换运算符的重载

        有一个Integer类,有一个实例a,执行:int x=a;显然是会出错的,此时可以重载类型转换运算符将类转换为其他类型。函数原型:  

                                                                           operator 类型名();

        可以看出,不能指定返回类型。例:operator int();

    五 ->运算符

    #include <iostream>
    using namespace std;
    
    class DBHelper
    {
    public:
        DBHelper()
        {
            cout << "DBHelper" << endl;
        }
        ~DBHelper()
        {
            cout << "~DBHelper" << endl;
        }
        void open()
        {
            cout << "open()" << endl;
        }
        void close()
        {
            cout << "close()" << endl;
        }
        void query()
        {
            cout << "query" << endl;
        }
    
    };
    
    class DB
    {
    public:
        DB()
        {
            db_ = new DBHelper;
        }
        ~DB()
        {
            delete db_;
        }
        DBHelper* operator->()
        {
            return db_;
        }
    private:
        DBHelper* db_;
    };
    
    int main()
    {
        DB db;
        db->open();
        db->query();
        db->close();
    
        return 0;
    }
  • 相关阅读:
    函数递归,匿名函数
    生成器
    迭代器
    有参函数(认证功能)
    闭包函数和装饰器
    文件处理
    Celery介绍
    Redis 介绍
    GIT知识点
    前后端分离-前端配置
  • 原文地址:https://www.cnblogs.com/lulu10922/p/5832491.html
Copyright © 2011-2022 走看看