关于函数运算符号重载函数

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

 

原文链接: https://www.cnblogs.com/yuguangyuan/p/6679605.html

欢迎关注

微信关注下方公众号,第一时间获取干货硬货;公众号内回复【pdf】免费获取数百本计算机经典书籍;

也有高质量的技术群,里面有嵌入式、搜广推等BAT大佬

    关于函数运算符号重载函数

原创文章受到原创版权保护。转载请注明出处:https://www.ccppcoding.com/archives/397841

非原创文章文中已经注明原地址,如有侵权,联系删除

关注公众号【高性能架构探索】,第一时间获取最新文章

转载文章受原作者版权保护。转载请注明原作者出处!

(0)
上一篇 2023年4月11日 上午9:47
下一篇 2023年4月11日 上午9:47

相关推荐