标题:C++的问题:使用基类成员函数的指针产生多态性,对输出结果不理解
只看楼主
wxz11191975
Rank: 1
等 级:新手上路
帖 子:98
专家分:0
注 册:2011-6-20
结帖率:85.29%
已结贴  问题点数:10 回复次数:3 
C++的问题:使用基类成员函数的指针产生多态性,对输出结果不理解
#include <iostream>
using namespace std;

class base{
public:
    virtual void print(){cout<<"In Base"<<endl;}
};

class derived:public base{
public:
    void print(){cout<<"In Derived"<<endl;}
};

void display(base *pb,void (base::*pf)())
{(pb->*pf)();}

void main(){
    derived d;
    base *pb=&d;
    void (base::*pf)();
    pf=base::print;
    display(pb,pf);
}
就这个程序,我以为它会出现“In Base”的,结果它给我看“In Derived”。不能理解,请求指点。谢谢!
搜索更多相关主题的帖子: 多态性 public include void 
2012-09-04 18:41
pangding
Rank: 19Rank: 19Rank: 19Rank: 19Rank: 19Rank: 19
来 自:北京
等 级:贵宾
威 望:94
帖 子:6784
专家分:16751
注 册:2008-12-20
得分:3 
只有静态函数成员才能取地址吧。这样写是不是应该不合法?楼主用的什么编译器?
2012-09-05 00:23
rjsp
Rank: 20Rank: 20Rank: 20Rank: 20Rank: 20
等 级:版主
威 望:507
帖 子:8890
专家分:53117
注 册:2011-1-18
得分:3 
首先代码语法就是错误的,其次,既然标题说了“……指针产生多态性”,为什么又对输出In Derived不理解?

程序代码:
#include <iostream>
using namespace std;

class base {
public:
    virtual void print() { cout<<"In Base"<<endl; }
};

class derived:public base{
public:
    virtual void print() { cout<<"In Derived"<<endl; }
};

void display( base* pb, void (base::*pf)() ) {
    (pb->*pf)();
}

int main() {
    derived d;
    base* pb = &d;
    void (base::*pf)() = &base::print;
    display( pb, pf );

    return 0;
}

2012-09-05 08:03
gaoyao469
Rank: 1
等 级:新手上路
帖 子:2
专家分:3
注 册:2012-7-18
得分:3 
#include <iostream>
using namespace std;

class base {
public:
    void print() { cout<<"In Base"<<endl; }
};

class derived:public base{
public:
    void print() { cout<<"In Derived"<<endl; }
};

void display( base* pb, void (base::*pf)() ) {
    (pb->*pf)();
}

int main() {
    derived d;
    base* pb = &d;
    void (base::*pf)() = &base::print;
    display( pb, pf );

    return 0;
}
2012-09-05 15:36



参与讨论请移步原网站贴子:https://bbs.bccn.net/thread-380685-1-1.html




关于我们 | 广告合作 | 编程中国 | 清除Cookies | TOP | 手机版

编程中国 版权所有,并保留所有权利。
Powered by Discuz, Processed in 0.246864 second(s), 8 queries.
Copyright©2004-2024, BCCN.NET, All Rights Reserved