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 继承修改:

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函数依然存在, 在内部依然可以使用;


dashoumeixi
15 声望1 粉丝