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

来源:互联网 发布:windows屏幕水印 编辑:程序博客网 时间:2024/05/17 19:57

一句话总结:利用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(constFunCallback_& 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();


    return0;

}



运行结果:

parent tall:180

I am child!

parent tall:170

I am child2!

Program ended with exit code: 0


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

原创粉丝点击