zoukankan      html  css  js  c++  java
  • 重载操作符- 友元函数- 非/模板类重载

    #include <iostream>
    #include <cstdio>
    #include <cstring>
    
    using namespace std;
    template <class T>
    class A;
    
    template <class T>
    ostream &operator<<(ostream &out, const A<T>&obj);
    
    template <class T>
    class A{
    public:
        A(int i):data(i){}
        friend ostream& operator<< <>(ostream &out, const A<T>&obj);
    private:
        T data;
    };
    
    template <class T>
    ostream &operator<<(ostream &out, const A<T>&obj)
    {
        out<<obj.data;
        return out;
    }
    class String{
    public:
        //构造函数
        String(const char* str = NULL){
            if(str == NULL){
                m_data = new char[1];
                m_data[0]='';
            }else{
                int length = strlen(str);
                m_data = new char[length];
                strcpy(m_data, str);
            }
        }
        //析构函数
        ~String(void){
            delete[] m_data;
        }
        //拷贝构造函数
        String(const String &other){
            if(other.m_data == NULL){
                m_data = new char[1];
                m_data[0]='';
            }else{
                int length = strlen(other.m_data);
                m_data = new char[length];
                strcpy(m_data, other.m_data);
            }
        }
        //赋值函数
        String operator=(const String &other){
            //自检
            if(this == &other){
                return *this;
            }
            delete []m_data;
            if(other.m_data == NULL){
                m_data = new char[1];
                m_data[0]='';
            }else{
                int length = strlen(other.m_data);
                m_data = new char[length];
                strcpy(m_data, other.m_data);
            }
            return *this;
        }
        friend ostream &operator<<(ostream &os, const String &s);
    private:
        char *m_data;
    
    };
    //重载输出
    ostream &operator<<(ostream &os, const String &s){
        os<<s.m_data;
        return os;
    }
    int main()
    {
        //模板类重载操作符
        A<int>a(2);
        cout<<a<<endl;
        //自实现String,包含构造函数,析构函数,拷贝构造函数,赋值函数。
        //重载操作符
        String s1("hello");
        String s2 = s1;
        cout<<s2<<endl;
        return 0;
    }
  • 相关阅读:
    互联网协议入门详解(转)
    文件流结尾的EOF详解
    数字签名是什么?
    SSL/TLS协议运行机制的概述(转)
    图解SSL/TLS协议(转)
    RSA算法原理(转)
    HTML代码简写法:Emmet和Haml(转)
    HTML Email 编写指南(转)
    PHP CodeBase: 判断用户是否手机访问
    Spring Data JPA之Derived query
  • 原文地址:https://www.cnblogs.com/luntai/p/5807879.html
Copyright © 2011-2022 走看看