c++ 虚函数

虚函数的默认参数值

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

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

#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

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

 

纯虚函数

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

 

转载于:https://www.cnblogs.com/rivsidn/p/9318193.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值