C 。下面这个程序是输出为什么是1,不是2

[复制链接]
查看11 | 回复1 | 2011-5-15 03:38:12 | 显示全部楼层 |阅读模式
#includeiostream
usingstd::cout;
usingstd::endl;

classA
{
        inta;
public:
        A*p;
public:
        A()
        {
                a=1;
                p=this;
        }
        voidprint()
        {
                coutaendl;
        }
};

classB:publicA
{
        intb;
public:
        B()
        {
                b=2;
        }
        voidprint()
        {
                coutbendl;
        }
};

Bbb;
A*afx()
{
        returnbb.p;
}

voidmain()
{
        A*q=afx();
        q-print();
}
回复

使用道具 举报

千问 | 2011-5-15 03:38:12 | 显示全部楼层
A是B的基类,q指向的是基类,用哪个指针就能访问哪个类的成员函数,在基类的print函数最前面加virtual试试
具体请了解多态相关知识
回复

使用道具 举报

您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

主题

0

回帖

4882万

积分

论坛元老

Rank: 8Rank: 8

积分
48824836
热门排行