public繼承中的虛函數與private/protected的區別

class Person{
public:
    virtual void test(){ cout << __FUNCTION__ << endl;}
};
class Student : public Person{
public:
    virtual void test() { cout << __FUNCTION__ << endl;}
};

void test_virtual(Person * p){...}

test_virtual(Student()) ; //沒問題吧

但只在public 繼承這纔沒問題 : Person * p = new Student函數

如今把 public 繼承修改:this

class Person{
public:
    virtual void test(){ cout << __FUNCTION__ << endl;}
};
class Student : protected Person{        //protected 繼承
public:
    virtual void test() { cout << __FUNCTION__ << endl;}
    
    //內部依然可使用virtual函數
    void test_virtual(){
        Person * p = this;
        p->test();
    }
};

如今呢 : Person p = new Student //conversion from 'Student ' to 'Person *' exists, but is inaccessible
緣由: 此時父類接口都是protected, 外部已經沒法訪問;
但virtual函數依然存在, 在內部依然可使用;code

相關文章
相關標籤/搜索