6、 继承 -- 基类 、派生类及virtual的用法

LibMat为基类,Book 是其派生类

当 LibMat 中print() 不加virtual时,普通函数print(),调用形参为LibMat, 实参为Book时,依然会调用LibMat类的print()成员函数,

只有当为virtual时,才会调用Book类的print()成员函数

注:普通函数 void print(const LibMat& mat) 形参为const, 当LibMat成员函数print(),不为const时会报错,即const类无法调用非const成员函数

#include <iostream> 
        
using namespace std;

class LibMat
{
    public:
        LibMat()
        {
            cout << "LibMat::LibMat() default constructor\n";
        }
        virtual ~LibMat()
        {
            cout << "LibMat::~LibMat() default destructor\n";
        }
        virtual void print() const          // 此处不加 virtual , 派生类每次调用时候,会调用此处基类的函数
        {
            cout << "LibMat.print() -- I'm a LibMat object" << endl;
        }
};

class Book : public LibMat
{
    public:
        Book(const string &title, const string &author)
            : _title(title), _author(author)
        {
            cout << "Book::Book( "<< _title <<", "<< _author << ")" << ": default constructor\n";
        }
        virtual ~Book()
        {
            cout << "Book::~Book() default destructor" << endl;
        }
        virtual void print() const          // const 一定要加, print参数为const ,const类调用非const成员函数会报错
        {   
            cout << "Book::print() -- I'm a Book object\n"
                 << "My title is " << _title << endl
                 << "My author is " << _author << endl;
        }   
        const string& title() const { return _title; }
        const string& author() const { return _author; }

    protected:
        string _title;
        string _author;
};

#if 1
void print(const LibMat &mat)
{
    cout << "global.print()" << endl;
    mat.print();
}
#else
// 采取模板的话就测不出 virtual功能, 因为传入的参数就为各自的,而不是形参是基类,实参是派生类
template <typename T>
void print(const T &t)
{
    cout << "global.print()" << endl;
    t.print();
}
#endif

int main()
{
#if 0
    cout << "create a LibMat object to print()" << endl;
    LibMat lm;
    print(lm);
#else
    cout << "create a Book object to print()" << endl;
    Book bk("LY", "yun");
    print(bk);

#endif

    return 0;
}

猜你喜欢

转载自blog.csdn.net/centnetHY/article/details/86521348