首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 开发语言 > C++ >

为什么指向虚成员函数的成员函数指针变量会有有关问题

2013-04-21 
为什么指向虚成员函数的成员函数指针变量会有问题?不才遇到一个看起来不应该有问题的问题,还请各位高人多

为什么指向虚成员函数的成员函数指针变量会有问题?
不才遇到一个看起来不应该有问题的问题,还请各位高人多多指教。

以下代码是从MSDN上拷下来并修改之后的,原始的代码是把函数指针bfnPrint放在Base类的外部定义的,就没有问题。我现在把bfnPrint定义在Base类的内部,使之成为一个成员变量,就出错了。编译后(Code::Block)在39行报以下错误:

error: 'bfnPrint' was not declared in this scope

请教各位大牛为什么会这样?要怎么实现用成员函数指针指向类的一个虚成员函数?谢谢!

//===============================================
class Base
{
public:
    Base();
    virtual void Print();
    void (Base ::* bfnPrint)();
};

Base :: Base() : bfnPrint(&Base :: Print)
{

}

void Base :: Print()
{
    cout << "Print function for class Base\n";
}

class Derived : public Base
{
public:
    void Print();  // Print is still a virtual function.
};

void Derived :: Print()
{
    cout << "Print function for class Derived\n";
}


int main()
{

    Base   *bPtr;
    Base    bObject;
    Derived dObject;
    bPtr = &bObject;    // Set pointer to address of bObject.
    (bPtr->*bfnPrint)();
    bPtr = &dObject;    // Set pointer to address of dObject.
    (bPtr->*bfnPrint)();

    return 0;
}

//===============================================


虚函数?成员函数指针
[解决办法]
(bPtr->*(bPtr->bfnPrint))();

热点排行