1. 程式人生 > >[C++]更改虛擬函式的訪問型別

[C++]更改虛擬函式的訪問型別

假設基類A定義了虛擬函式foo,訪問型別為public,

派生類B從A繼承,重寫foo,並修改訪問型別為protected

派生類C從A繼承,重寫foo,並修改訪問型別為private

在這種情況下,依然可以通過A指標訪問B和C的foo函式

#include<iostream>

using namespace std;

class A{
public:
	virtual void foo(){
		cout << "A::foo" << endl;
	}
};

class B : public A{
protected:
	void foo() override{
		cout << "B::foo" << endl;
	}
};

class C : public A{
private:
	void foo() override{
		cout << "C::foo" << endl;
	}
};


int main()
{
	A *pB = new B;
	A *pC = new C;

	pB->foo();
	pC->foo();

	return 0;
}

程式輸出為:

B::foo
C::foo