zoukankan      html  css  js  c++  java
  • 初探C++运算符重载学习笔记<2> 重载为友元函数

    初探C++运算符重载学习笔记 

     

    在上面那篇博客中,写了将运算符重载为普通函数类的成员函数这两种情况。

     

    以下的两种情况发生。则我们须要将运算符重载为类的友元函数

    <1>成员函数不能满足要求

    <2>普通函数又不能訪问类的私有成员时

     

     

    举例说明:

    class Complex{
        double real, imag;
        public:
        Complex(double r, double i):real(r), imag(i){ }; 
        Complex operator+(double r);   
    };
        Complex Complex::operator+(double r){
    
        return Complex(real + r, imag); 
    }
    

     

    定义一个复数类。重载'+'运算符,经过重载之后

    Complex c ;
    c = c + 5;  //有定义,相当于 c = c.operator +(5);
    
     

    可是假设出现5+c,则编译出问题。此时还须要重载普通函数。

    Complex operator+ (double r, const Complex & c) {
        return Complex( c.real + r, c.imag);
    }


    能解释 5+c,可是普通函数无法訪问类的私有成员。

     

    这时就须要重载为类的友元函数

    class Complex {
        double real, imag;
        public:
        Complex( double r, double i):real(r),imag(i){ }; 
        Complex operator+( double r );
        friend Complex operator + (double r, const Complex & c);
    };


     


     

     

     

  • 相关阅读:
    MVC框架简介
    模型-视图-控制器模式
    高德地图基本开发
    质量属性的六个常见属性场景分析
    架构漫谈读后感
    第十周
    第九周总结
    第八周总结
    springboot基于mybatis的pegehelper分页插件
    webmagic之爬取数据存储为TXT
  • 原文地址:https://www.cnblogs.com/lxjshuju/p/7120285.html
Copyright © 2011-2022 走看看