首页 > 编程语言 > 详细

c++ 虚函数

时间:2018-07-17 15:31:45      阅读:230      评论:0      收藏:0      [点我收藏+]

虚函数的默认参数值

如果虚函数在基类中的声明带有默认变元值,则通过基类指针调用该函数时,就总是从函数的基类模板中接受默认的变元值。

函数派生类版本中的默认值不起作用。

#include <iostream>

class Box {
    private :
    protected :
        double length = 1.0;
        double width = 1.0;
        double heigth = 1.0;
    public :
        Box() {};
        Box(double lengthValue, double widthValue, double heigthValue) {
            length = lengthValue;
            width = widthValue;
            heigth = heigthValue;
        }

        void show_volume() {
            std::cout << "volume is " << volume() << std::endl;
        }
        
        virtual double volume(int i = 50) {
            std::cout << i << std::endl;
            return length*width*heigth;
        }
};

class Carton:public Box {
    private :
    protected :
    public :
        Carton() {};
        Carton(double lengthValue, double widthValue, double heigthValue) : Box(lengthValue, widthValue, heigthValue) {};

        double volume(int i = 500) override {
            std::cout << i << std::endl;
            return 0.85*length*width*heigth;
        }            
};

int main()
{
    Box aBox{20, 30, 40};
    Carton aCarton{20, 30, 40};
    
    Box* pBox(&aCarton);
    
    std::cout << "carton volume is " << pBox->volume() << std::endl;

    return 0;
}

$ ./virtual
50
carton volume is 20400

有虚函数的对象占用的字节数要比没有虚函数的对象多。

 

纯虚函数

在基类中没有定义的虚函数,包含虚函数的类称为抽象类。

 

c++ 虚函数

原文:https://www.cnblogs.com/rivsidn/p/9318193.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!