c++中void*指针的转换打印问题

C++语言 码拜 9年前 (2015-10-22) 2215次浏览
有四个类,Base,Child,GrandChild,Base1这个四个类,然后Base中有一个virtual f()函数,child中没有覆写这个函数,在grandchild中覆写了这个函数,grandchild继承了base1和child类,base1中没有任何东西。
在main中什么都没打印出来,不知道为什么会这样。但是在class GrandChild:public Base1,public Child中换一下Base1和Child的位置的话,就可以打印出来grandchild.f()。

#ifndef BASE_H
#define BASE_H
class Base
{
    public:
        Base();
        virtual void f();   //实现为打印base.f()
        virtual ~Base();
};
#endif // BASE_H
#ifndef CHILD_H
#define CHILD_H
#include "Base.h"
class Child:public Base
{
    public:
        Child();
        virtual ~Child();
    protected:
    private:
};
#endif // CHILD_H
#ifndef GRANDCHILD_H
#define GRANDCHILD_H
#include<Child.h>
#include<Base1.h>
class GrandChild:public Base1,public Child
{
    public:
        GrandChild();
        virtual void f();   //打印grandchild.f()
        virtual ~GrandChild();
    protected:
    private:
};
#endif // GRANDCHILD_H
#ifndef BASE1_H
#define BASE1_H
class Base1
{
    public:
        Base1();
        virtual ~Base1();
    protected:
    private:
};
#endif // BASE1_H
#include <iostream>
#include<Base.h>
#include<GrandChild.h>
using namespace std;
int main()
{
    void *v = new GrandChild();
    Base *b = (Base*)v;
    b->f();//什么都没打印出来
    return 0;
}
解决方案:40分
 void *v = new GrandChild();
Base *b = (GrandChild*)v;

CodeBye 版权所有丨如未注明 , 均为原创丨本网站采用BY-NC-SA协议进行授权 , 转载请注明c++中void*指针的转换打印问题
喜欢 (0)
[1034331897@qq.com]
分享 (0)