• C++ 类模板二(类模版与友元函数)


    //类模版与友元函数
    #include<iostream>
    using namespace std;
    
    template<typename T>
    class Complex{
    public:
        Complex(T a,T b);
        void Print() const//const修饰的是this指针
        {
            cout << this->Real << ":" <<this->Image<< endl;
        }
        /*
        强调:在类模板里实现友元函数 不可以写在类的外部,只能在类的内部实现,否则编译器报错
        本质原因是类模板编译了2次,导致对友元函数也编译了2次 所以c++编译器不认可写在类模板外面的友元函数
        对于普通类则没有这个问题
        */
        //友元函数
        friend Complex operator+(Complex &c1, Complex &c2){
            Complex tempc(c1.Real + c2.Real, c1.Image + c2.Image);
            return tempc;//匿名对象
        }
        //成员函数---成员函数跟友元函数不同,可以在类外面实现
        Complex operator-(Complex &c2);
    private:
        T Real, Image;
    };
    
    template<typename T>
    Complex<T>::Complex(T a, T b){
        this->Real = a;
        this->Image = b;
    }
    
    template<typename T>
    Complex<T> Complex<T>::operator-(Complex<T> &c2){
        Complex tempc(this->Real - c2.Real, this->Image - c2.Image);
        return tempc;//匿名对象
    }
    
    
    void ProtectA(){
        Complex<int> c1(3,4);
        //c1.Print();
        Complex<int> c2(5, 7);
        //运算符重载 +  友元函数实现
        Complex<int> c3 = c1 + c2;
        c3.Print();
        /*
        首先承认运算符重载是一个函数,写出函数名
        operator+
        然后根据操作数,写出参数列表
        operator+(Complex<int> &c1,Complex<int> &c2)
        最后根据接收对象决定返回值,实现函数
        Complex<int> operator+(Complex<int> &c1,Complex<int> &c2)
        在类的内部可以省略参数列表,因为类的声明不分配内存,不需要确定类的大小
        */
        Complex<int> c4 = c2 - c1;
        /*
        首先承认运算符重载是一个类内部函数,写出函数名
        operator-
        然后根据操作数,写出参数列表
        c1.operator-(Complex<int> &c2);
        最后根据接收对象决定返回值,实现函数
        Complex<int> c1.operator-(Complex<int> &c2);
        在类的内部可以省略参数列表,因为类的声明不分配内存,不需要确定类的大小
        */
        c4.Print();
        
    }
    
    void main(){
        ProtectA();
        system("pause");
    }
  • 相关阅读:
    JSP学习-10-EL表达式
    深入浅出Mybatis(一)
    第10章—开启事务
    第09章—使用Lombok插件
    第08章—整合Spring Data JPA
    第06章—热部署
    第05章—Swagger2打造在线接口文档
    第03章—打造RESTful风格API
    第04章—整合Mybatis
    第01章—快速构建
  • 原文地址:https://www.cnblogs.com/zhanggaofeng/p/5661829.html
Copyright © 2020-2023  润新知