一個虛函數(shù)的訪問權(quán)限問題
Posted on 2006-06-28 11:42 mahudu@cppblog 閱讀(489) 評論(2) 編輯 收藏 引用 所屬分類: C/C++在水木上見到一個貼子,關(guān)于虛函數(shù)的訪問權(quán)限問題:
#include<cstdlib>

#include<iostream>

using?namespace?std;

?


class?B?
{

public:


???virtual?int?f1()
{cout<<"B::f1()"<<endl;return?0;}


???virtual?void?f2(?int?val)
{cout<<"B::f2(int)"<<endl;}


???virtual?int?f3(?int?val?)
{cout<<"B::f3(int)"<<endl;return?0;}

};

?


class?D?:?public?B?
{


???int?f1()
{cout<<"D::f1()"<<endl;return?0;}


???virtual?void?f4()
{cout<<"D::f4()"<<endl;}


???int?f3(int?val)
{cout<<"D::f3(int)"<<endl;return?0;}

};

?

int?main(int?argc,?char?*argv[])



{

???B?*bp?=?new?D;

???bp->f3(12);//D中的f3是private的,可以訪問#1

???D?*dp=new?D;

???dp->f3(12);//f3是private,訪問不了,編譯通不過

???system("PAUSE");

???return?EXIT_SUCCESS;

}

其實(shí)這是一個關(guān)于訪問權(quán)限決定時(shí)間的問題,由于訪問權(quán)限是編譯時(shí)間決定的,而不是運(yùn)行時(shí)決定的。
B *bp = new D;??// 此時(shí)bp所指向的類型是B而不是D,而B的f3()是公有的,所以可以訪問。
D *dp = new D; // 此時(shí)dp所指向的類型是D,而D的f3()是私有的,所以不能訪問。






































































其實(shí)這是一個關(guān)于訪問權(quán)限決定時(shí)間的問題,由于訪問權(quán)限是編譯時(shí)間決定的,而不是運(yùn)行時(shí)決定的。
B *bp = new D;??// 此時(shí)bp所指向的類型是B而不是D,而B的f3()是公有的,所以可以訪問。
D *dp = new D; // 此時(shí)dp所指向的類型是D,而D的f3()是私有的,所以不能訪問。