zoukankan      html  css  js  c++  java
  • 关于函数运算符号重载函数

    class A{
    public:
        typedef int (*func)(int);
        operator func();
    };
    int ff(int a){
        return a;
    }

    A::operator func(){
        return ff;
    }

    int main () {
        cout<< A::func(9)<<endl;//运算符号 func() 这个func是typedef类型的。 调用的时候指定作用域
    }

    //运算符重载:成员函数方式
    #include <iostream>
    using namespace std;
    
    class complex //复数类
    {
    public:
        complex(){ real = imag = 0;}
        complex(double r, double i)
        {
            real = r;
            imag = i;
        }
        complex operator + (const complex &c);
        complex operator - (const complex &c);
        complex operator * (const complex &c);
        complex operator / (const complex &c);
    
        friend void print(const complex &c); //友元函数
    
    private:
        double real; //实部
        double imag; //虚部
    
    };
    
    inline complex complex::operator + (const complex &c) //定义为内联函数,代码复制,运算效率高
    {
        return complex(real + c.real, imag + c.imag);
    }
    
    inline complex complex::operator - (const complex &c)
    {
        return complex(real - c.real, imag - c.imag);
    }
    
    inline complex complex::operator * (const complex &c)
    {
        return complex(real * c.real - imag * c.imag, real * c.real + imag * c.imag);
    }
    
    inline complex complex::operator / (const complex &c)
    {
        return complex( (real * c.real + imag * c. imag) / (c.real * c.real + c.imag * c.imag), 
            (imag * c.real - real * c.imag) / (c.real * c.real + c.imag * c.imag) );
    }
    
    void print(const complex &c) 
    {
        if(c.imag < 0)
            cout<<c.real<<c.imag<<'i'<<endl;
        else
            cout<<c.real<<'+'<<c.imag<<'i'<<endl;
    }
    
    int main()
    {    
        complex c1(2.0, 3.5), c2(6.7, 9.8), c3;
        c3 = c1 + c2;
        cout<<"c1 + c2 = ";
        print(c3); //友元函数不是成员函数,只能采用普通函数调用方式,不能通过类的对象调用
    
        c3 = c1 - c2;
        cout<<"c1 - c2 = ";
        print(c3);
    
        c3 = c1 * c2;
        cout<<"c1 * c2 = ";
        print(c3);
    
        c3 = c1 / c2;
        cout<<"c1 / c2 = ";
        print(c3);
        return 0;
    }
    View Code
  • 相关阅读:
    南阳33(蛇形填数)规律题;
    南阳241(字母统计)
    南阳57(6174问题)
    android图形基础知识
    Linux中yum手动安装、手动建立仓库文件夹关联实现关联包自动安装、yum相关命令使用
    debug连线指令
    Qt之信号连接,你Out了吗?
    hdu-4607-Park Visit
    MySQL 分区表 partition线上修改分区字段,后续进一步学习partition (1)
    如何用正则将多个空格看成一个空格结合spllit()方法将文本数据入库
  • 原文地址:https://www.cnblogs.com/yuguangyuan/p/6679605.html
Copyright © 2011-2022 走看看