基于面向对象的编程的优势与劣势

一句话总结:利用boost::bind可以让回调函数更加灵活易用,不局限于函数类型及参数个数;然后无法像面向对象的虚函数那样可以一类功能中灵活扩展。

#include <iostream>

#include <boost/bind.hpp>

#include <boost/noncopyable.hpp>

#include <boost/function.hpp>


typedef boost::function<void ()> FunCallback_;


class Parent : boost::noncopyable

{

    

public:

    

    Parent(int tall):tall_(tall){}

    ~Parent(){}

    

    void setFunCallback(const FunCallback_& cb)

    {

        funcallback_ = cb;

    }

    void start()

    {

        printf("parent tall:%d\n", tall_);

        funcallback_();

    }

    

private:

    FunCallback_ funcallback_;

    int tall_;

};


class Child : boost::noncopyable

{

public:

    Child(int age)

    :age_(age),

     parent_(180)

    {

        parent_.setFunCallback(boost::bind(&Child::print, this));

    }

    ~Child(){}

    

    void print()

    {

        printf("I am child!\n");

    }

    

    void start()

    {

        parent_.start();

    }


private:

    int age_;

    Parent parent_;

};


class Child2 : boost::noncopyable

{

public:

    Child2(int age)

    :age_(age),

    parent_(170)

    {

        parent_.setFunCallback(boost::bind(&Child2::print, this));

        

    };

    ~Child2(){}

    

    void print()

    {

        printf("I am child2!\n");

    }

    

    void start()

    {

        parent_.start();

    }

    

private:

    int age_;

    Parent parent_;

};


int main(int argc, const char * argv[]) {

    // insert code here...

    Child child(22);

    Child2 child2(23);

    child.start();

    child2.start();


    return 0;

}



运行结果:

parent tall:180

I am child!

parent tall:170

I am child2!

Program ended with exit code: 0


说明每个child各有一份parent实体,与面向对象一样。

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值