技术,瞎侃,健康,休闲……

mahu@cppblog 人类的全部才能无非是时间和耐心的混合物
posts - 11, comments - 13, trackbacks - 0, articles - 12
  C++博客 :: 首页 :: 新随笔 :: 联系 :: 聚合  :: 管理

一个虚函数的访问权限问题

Posted on 2006-06-28 11:42 mahudu@cppblog 阅读(450) 评论(2)  编辑 收藏 引用 所属分类: C/C++
在水木上见到一个贴子,关于虚函数的访问权限问题:

#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;

}


其实这是一个关于访问权限决定时间的问题,由于访问权限是编译时间决定的,而不是运行时决定的。
B *bp = new D;  // 此时bp所指向的类型是B而不是D,而B的f3()是公有的,所以可以访问。
D *dp = new D; // 此时dp所指向的类型是D,而D的f3()是私有的,所以不能访问。

Feedback

# re: 一个虚函数的访问权限问题[未登录]  回复  更多评论   

2007-05-31 16:02 by Joe
好难啊~~~晕了~~~

# re: 一个虚函数的访问权限问题  回复  更多评论   

2008-08-10 10:17 by AlexEric
巧妙!

只有注册用户登录后才能发表评论。
网站导航: 博客园   IT新闻   BlogJava   知识库   博问   管理