C++ 细节(一)———->关于自定义Functor以及重载operator=

先上代码:

//printer.hpp 

#ifndef PRINTER_HPP_
#define PRINTER_HPP_

typedef void (*pfunc)(int);
class printer
{
public:
    printer();
    printer(pfunc func);
    virtual ~printer(void);
    printer& operator=(pfunc func);
    bool operator()(int elem);
private:
    pfunc m_func;
};
#endif

//printer.cpp
#include "printer.hpp"

printer::printer():m_func(0)
{
}

printer::printer(pfunc func):m_func(func)
{
}

printer::~printer(void)
{
}

printer& printer::operator=(pfunc func)
{
    m_func = func;
    return *this;
}

bool printer::operator()(int elem)
{
    if(!m_func)
        return false;
    else
    {
        (*m_func)(elem);
        return true;
    }
}

//main.cpp
{
    printer p = &printint;
    p(10);
}

 

 代码仅有这么几行,要点在于:

1.想实现在main.cpp中的用法,必须重载构造函数,使其可以接收pfunc类型

不然只能写成

printer p;

p = &printint;

2.对于operator=,返回值必须是同类型对象,不然会类型不匹配

原文链接: https://www.cnblogs.com/phoewang/archive/2012/03/15/2398368.html

欢迎关注

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

    C++ 细节(一)---------->关于自定义Functor以及重载operator=

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

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

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

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

(0)
上一篇 2023年2月8日 下午8:53
下一篇 2023年2月8日 下午8:54

相关推荐