+ -
当前位置:首页 → 问答吧 → boost::function绑定继承派生类

boost::function绑定继承派生类

时间:2011-12-18

来源:互联网

以下代码问题:
boost::function<void(CBase*, const std::string&)> Func1; //why can't be CBase
CDerive derive;
Func1 = &CDerive::print;
Func1(dynamic_cast<CBase*>(&derive), "3");

问题: 为什么不能讲派生类指针转化为基类指针,然后调用Func1(dynamic_cast<CBase*>(&derive), "3");

#include <iostream>
#include <string>
#include <boost/function.hpp>
#include <vector>

class CBase {
public:
CBase(){}
virtual ~CBase(){}

public:
virtual void print(const std::string& vInfo) {std::cout << "base class member print function:" << vInfo << std::endl;}
};

class CDerive : public CBase {
public:
CDerive(){}
virtual ~CDerive(){}

public:
virtual void print(const std::string& vInfo) {std::cout << "derive class member print function:" << vInfo << std::endl;}
};

void globalPrint(const std::string& vInfo)
{
std::cout << "global print function:" << vInfo << std::endl;
}

class FunctionObj {
public:
FunctionObj(){}
~FunctionObj(){}

public:
void operator()(const std::string& vInfo) {std::cout << "function object print function:" << vInfo << std::endl;}
};


int main (int argc, char * const argv[]) {
  // insert code here...
std::vector<boost::function<void(const std::string&)> > FuncVec;
FuncVec.push_back(&globalPrint);
FuncVec.push_back(FunctionObj());
FuncVec[0]("0");
FuncVec[1]("1");
boost::function<void(CBase*, const std::string&)> Func0;
Func0 = &CBase::print;
CBase base;
Func0(&base, "2");
boost::function<void(CBase*, const std::string&)> Func1; //why can't be CBase
CDerive derive;
Func1 = &CDerive::print;
Func1(dynamic_cast<CBase*>(&derive), "3");
  return 0;
}

作者: lpcudaid   发布时间: 2011-12-18

到底几个问题啊?

作者: taodm   发布时间: 2011-12-18