zoukankan      html  css  js  c++  java
  • 《新标准C++程序设计》4.4(C++学习笔记14)

    运算符重载为友元函数

    一般情况下,将运算符重载为类的成员函数,是较好的选择。 

    但有时,重载为成员函数不能满足使用要求,重载为普通函数,又不能访问类的私有成员,所以需要将运算符重载为友元。

    class Complex
    {
    double real,imag;
    public:
    Complex( double r, double i):real(r),imag(i){ };
    Complex operator+( double r );
    };
    Complex Complex::operator+( double r )
    { //能解释 c+5
    return Complex(real + r,imag);
    }

    经过上述重载后:

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

    但是:

    c = 5 + c; //编译出错

    所以,为了使得上述的表达式能成立,需要将 + 重载为普通函数。

    Complex operator+ (double r,const Complex & c)
    { //能解释 5+c
    return Complex( c.real + r, c.imag);
    }

    但是普通函数又不能访问私有成员,所以,需要将运算符 + 重载为友元。

    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);
    };
  • 相关阅读:
    js-url打开方式
    eclipse删除所有空行
    Oracle重启 error: ora-01034:oracle not available ora-27101:shared memory realm does not exist
    最近面试遇到了高阶函数的概念混乱了
    关于跨域的cookie问题
    二叉树 呜呜
    函数的尾递归
    react context
    二叉树
    dom3级事件
  • 原文地址:https://www.cnblogs.com/cyn522/p/12301033.html
Copyright © 2011-2022 走看看