首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >为什么从基本类型转换到派生类型会提供这样的功能?

为什么从基本类型转换到派生类型会提供这样的功能?
EN

Stack Overflow用户
提问于 2018-09-05 07:47:45
回答 1查看 76关注 0票数 -1

我不明白为什么在我没有使用virtual关键字的情况下,将派生类强制转换为基类的指针会调用派生类方法。这是正常行为吗?指针不是将Person对象保存在内存中,因此将其传递给Student应该不会对其内容产生任何影响?

代码语言:javascript
运行
复制
  class Person {

    public:

    Person()
    {
        cout << "Creating Person Class" << endl;
    }

    void about_me()
    {
        cout << "I am a person" << endl;
    }
};

class Student : protected Person {
    public:
    Student()
    {
        cout << "Creating Student Class" << endl;
    }

    void about_me()
    {
        cout << " I am a student " << endl;
    }

};

int main()
{
    Person* pperson = new Person();
    Student* pstudent = new Student();

    pperson->about_me();
    pstudent->about_me();

    pperson-> about_me();

    ((Student*)pperson)-> about_me(); // this is the line where I do the cast

    return 0;

}

代码的输出如下所示

代码语言:javascript
运行
复制
  Creating Person Class
Creating Person Class
Creating Student Class
I am a person
 I am a student 
I am a person
 I am a student
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/52175292

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档