重载操作符- 友元函数- 非/模板类重载

#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;
}
原文地址:https://www.cnblogs.com/luntai/p/5807879.html