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

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

 

纯虚函数

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

 

posted on 2018-07-17 13:56  rivsidn  阅读(117)  评论(0)    收藏  举报

导航