在继承中派生类成员函数的访问权限测试
派生类对自身基类的private成员没有访问权限,对基类对象的protected成员没有访问权限,对派生类对象的(基类之外)的private和protected成员具有访问权限。
由于C++基础不好,平时也不用它,导致今天才纠正一个非常关键的错误,类的访问权限,是对类而言的,而不是对类的对象而言的。一直都理解错了。这句话都没脸写出来,还是写下来了。
下面是一段简答的测试代码。对于调用成员函数的对象test,基类形参,派生类形参三者的访问权限做了测试如下:
- #include <iostream>
- usingnamespace std;
- class base
- {
- public:
- int pub;
- protected:
- int pro;
- private:
- int pri;
- };
- class derive : public base
- {
- public:
- int newpub;
- protected:
- int newpro;
- private:
- int newpri;
- public:
- int func(class base a, class derive b)
- {
- //////////////////////////////////////////
- 自身的 基类成员和非基类成员访问权限测试
- cout << newpub << endl;
- cout << newpro << endl;
- cout << newpri << endl;
- cout << pub << endl;
- cout << pro << endl;
- // no access cout << pri << endl;
- /////////////////////////////////////////
- 对基类对象访问权限的测试
- cout << a.pub << endl;
- // no access cout << a.pro << endl;
- // no access cout << a.pri << endl;
- /////////////////////////////////////////
- 对派生类对象的基类以及非基类成员访问权限测试
- cout << b.pub << endl;
- cout << b.pro << endl;
- //no access cout << b.pri << endl;
- cout << b.newpub << endl;
- cout << b.newpro << endl;
- cout << b.newpri << endl;
- ////////////////////////////////////////
- return 0;
- }
- };
- int main()
- {
- class base a;
- class derive b;
- class derive test;
- test.func(a, b);
- return 0;
- }
#include <iostream>
using namespace std;
class base
{
public:
int pub;
protected:
int pro;
private:
int pri;
};
class derive : public base
{
public:
int newpub;
protected:
int newpro;
private:
int newpri;
public:
int func(class base a, class derive b)
{
//////////////////////////////////////////
自身的 基类成员和非基类成员访问权限测试
cout << newpub << endl;
cout << newpro << endl;
cout << newpri << endl;
cout << pub << endl;
cout << pro << endl;
// no access cout << pri << endl;
/////////////////////////////////////////
对基类对象访问权限的测试
cout << a.pub << endl;
// no access cout << a.pro << endl;
// no access cout << a.pri << endl;
/////////////////////////////////////////
对派生类对象的基类以及非基类成员访问权限测试
cout << b.pub << endl;
cout << b.pro << endl;
//no access cout << b.pri << endl;
cout << b.newpub << endl;
cout << b.newpro << endl;
cout << b.newpri << endl;
////////////////////////////////////////
return 0;
}
};
int main()
{
class base a;
class derive b;
class derive test;
test.func(a, b);
return 0;
}
聚拓互联(http://www.ejutuo.com).Net平台至强虚拟主机供应商,是领先的互联网基础应用服务提供商,主要面向全球客户提供域名注册、国内、香港/美国虚拟主机、企业邮箱、智能建站、虚拟服务器(VPS)、服务器租用、服务器托管等丰富的网络产品服务。
聚拓互联的快速发展与其企业文化密不可分,易网人秉持“团结互助、敬业负责、恪守信誉、积极进取、勇于创新”的企业文化,汇聚了行业内的大量专业人士,拥有多位国内顶尖的linux/freeBSD/unix经验的系统工程师、微软认证工程师和网络安全技术人才。核心团队均为该行业从业多年的专业人士,拥有丰富行业经验和较高威望,并不断改革创新,以满足客户多元化需求为己任,不断进取。 同时,易网坚守 “专业品质、服务为本、诚信经营、恪守信誉”的核心价值观,为客户提供多样、安全、稳定、放心的产品。
浙公网安备 33010602011771号