码迷,mamicode.com
首页 > 编程语言 > 详细

c++ 虚函数

时间:2018-07-17 16:45:21      阅读:172      评论:0      收藏:0      [点我收藏+]

标签:box   col   include   基类指针   amp   virt   调用   rtu   double   

虚函数的默认参数值

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

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

#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++ 虚函数

标签:box   col   include   基类指针   amp   virt   调用   rtu   double   

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

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!