虚拟和非虚拟成员函数的调用方式之间有什么区别? [英] What's the difference between how virtual and non-virtual member functions are called?

查看:127
本文介绍了虚拟和非虚拟成员函数的调用方式之间有什么区别?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

#include<iostream>
using namespace std;
int main(){
    class c1{

        public:
         int func(){
            cout<<"in the  c1";
         }

    };

    class c2:public c1{

        public:
        int func(){
            cout<<" in c2";
        }
    };


c1* a;
c2 b;

a=&b;
a->func();

}

我知道我应该使用虚函数来获得期望的结果,但是我想知道上面代码中发生了什么.即为什么要调用c1 :: func()而不是c2 ::: func()?

I Know i should have used virtual functions to get the desired result but i want to know what is going on in the above code.i.e Why is the call to c1::func() is being made instead of c2::func()?

另外,请说明使用virtual时与这种情况不同的情况.

Also please explain what happens when virtual is used that is different from this case.

推荐答案

当成员函数不是virtual时,调用的函数仅由点左侧(.)表达式的类型确定.或箭头(->)运算符.这称为静态类型".

When a member function is not virtual, the function called is determined only by the type of the expression to the left of the dot (.) or arrow (->) operator. This is called the "static type".

当成员函数为virtual时,所调用的函数由对象的最实际派生类型确定,该对象的类型由点(.)左侧的表达式命名或由箭头左侧的表达式( ->).这就是所谓的动态类型".

When a member function is virtual, the function called is determined by the actual most derived type of the object named by the expression left of the dot (.) or pointed to by the expression left of the arrow (->). This is called the "dynamic type".

请注意,当圆点左侧使用的变量,成员,参数或返回类型具有普通类类型时,静态类型和动态类型始终相同.但是,如果变量,成员,参数或返回类型是指针或对类类型的引用,则静态类型和动态类型可以不同.

Note that when a variable, member, parameter, or return type used to the left of a dot has a plain class type, the static type and dynamic type are always the same. But if a variable, member, parameter, or return type is a pointer or reference to a class type, the static type and dynamic type can be different.

这篇关于虚拟和非虚拟成员函数的调用方式之间有什么区别?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆