public继承中的虚函数与private/protected的区别

14次阅读

共计 615 个字符,预计需要花费 2 分钟才能阅读完成。

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

正文完
 0