使虚函数成为虚拟函数有什么用,为什么我们不能使任何函数成为虚函数? [英] What is the use of making virtual function and why we can not make any function as virtual?

查看:106
本文介绍了使虚函数成为虚拟函数有什么用,为什么我们不能使任何函数成为虚函数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

制作虚拟函数的用途是什么,为什么我们不能将任何函数虚拟化?

What is the use of making virtual function and why we can not make any function as virtual?

推荐答案

例如,您有一个名为Shape和您有一个函数CalculateArea.并非所有形状都会以相同的方式计算面积,因此在您的基类中会这样;

As an example say you have a class called Shape and you have a function CalculateArea. Not all shapes will calculate the area in the same way so in your base class you would;

class Shape
{
    public:
        virtual double CalculateArea() { width * height; }
} 



然后在派生类中,您将;



Then in your derived class you would;

class Circle : Shape
{
    public:
        virtual double CalculateArea() { pi * radius * radius; }
}



您只能在有意义的地方使函数虚拟化.



You only make functions virtual where it makes sense.


虚拟函数是多态性"的基础,您应该查询一下或询问您的讲师,为什么多态性在OOP中很重要.

不能阻止您将每个函数都声明为虚拟的,但是取决于编译器,如此声明的每个函数的对象实例化都会更大.
Virtual Functions are the basis for "polymorphism", you should look that up or ask your instructor why polymorphism is important in OOP.

There is nothing from stopping you from declaring *every functions* to be virtual but, depending on the compiler, the object instantiation will be larger for each function so declared.


总之:因为它们是两件事.

再长一点,考虑一下,看看say_hellosay_vhello表现如何重复到A*.


In brief: because they are two different things.

In longer, consider this, and look how say_hello and say_vhello behave respet to A*.


#include <iostream>

class A
{
public:
    virtual void vhello() 
    { std::cout << "I''m A::vhello" << styd::edl; }
    
    void hello() 
    { std::cout << "I''m A::hello" << styd::edl; }
};

class B: public A
{
public:
    virtual void vhello() 
    { std::cout << "I''m B::vhello" << styd::edl; }
    
    void hello() 
    { std::cout << "I''m B::hello" << styd::edl; }
};

void say_hello(A* pa)
{ pa->hello(); }

void say_vhello(A* pa)
{ pa->vhello(); }

int main()
{
    A a;
    B b;    // remebre B <b>is a</b> A
    
    say_hello(&a);   //call A::hello
    say_hello(&b);   //convert B* to A*, call A::hello
    
    say_vhello(&a);  //seek vtable for vhello, call A::vhello 
    say_vhello(&b);  //convert B* to A*, seek vtable for vhello, call B::vhello
    
    return 0; 
}


这篇关于使虚函数成为虚拟函数有什么用,为什么我们不能使任何函数成为虚函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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