第一:private, public, protected 访问标号的访问范围。
private:只能由1.该类中的函数、2.其友元函数访问。
不能被任何其他访问,该类的对象也不能访问。
举例如下:
// public_protect_private.cpp : 定义控制台应用程序的入口点。
//
#include "stdafx.h"
#include <iostream>
using namespace std;
class Base
{
public:
Base(int i)
{
tmp=i;
};
~Base()
{
cout<<"program exit\n"<<tmp<<endl;
}
private:
int tmp;
int tmp2;
public:
void SetValue(int j)
{
tmp2=j;
return;
}
void PrintValue()
{
cout<<"tmp2 is"<<tmp2<<endl;
}
};
int _tmain(int argc, _TCHAR* argv[])
{
Base p(1);
p.SetValue(100);
p.PrintValue();
//p.tmp2=455; // error C2248: “Base::tmp2”: 无法访问private 成员(在“Base”类中声明)
//p.PrintValue();
return 0;
}
但是注意如果是在同一个类中是可以访问私有变量的。特别注意线程中的时候,比如给线程传递一个this,在线程里面使用this->flag是可以的。Flag为私有变量。
protected:可以被1.该类中的函数、2.子类的函数、以及3.其友元函数访问。
但不能被该类的对象访问。
如果将上例中的
int tmp;
int tmp2;
改为protected:那么该类的对象也不能访问。error C2248: “Base::tmp2”: 无法访问protected 成员(在“Base”类中声明),private和protected对基类来说是一样 ,protected对派生类的访问权限和private不同。下面看看,在派生类的成员函数中能访问基类的protected数据成员吗?
protected:
int tmp;
int tmp2;
程序如下:
// public_protect_private.cpp : 定义控制台应用程序的入口点。
//
#include "stdafx.h"
#include <iostream>
using namespace std;
class Base
{
public:
Base(int i)
{
tmp=i;
};
~Base()
{
cout<<"program exit\n"<<tmp<<endl;
}
protected:
int tmp;
int tmp2;
public:
void SetValue(int j)
{
tmp2=j;
return;
}
void PrintValue()
{
cout<<"tmp2 is"<<tmp2<<endl;
}
};
class Inherit:protected Base
{
public:
Inherit(int i):Base(i)
{
tmp3=i;
};
~Inherit()
{
cout<<"Inherit program exit\n"<<tmp3<<endl;
}
private:
int tmp3;
int tmp4;
public:
void InheritSetBaseValue(int j)
{
tmp2=j;
return;
}
void InheritPrintBaseValue()
{
cout<<"tmp2 is"<<tmp2<<endl;
}
void InheritSetValue(int j)
{
tmp4=j;
return;
}
void InheritPrintValue()
{
cout<<"tmp4 is"<<tmp4<<endl;
}
void InheritPrintThoughBase()
{
PrintValue();
}
};
int _tmain(int argc, _TCHAR* argv[])
{
Base p(1);
p.SetValue(100);
p.PrintValue();
//p.tmp2=455; //error不能访问base类中保护成员变量
Inherit q(200);
q.InheritSetValue(300);
q.InheritPrintValue();
q.InheritSetBaseValue(400); //ok ,派生类中共有成员函数访问基类的protected成员变量,因为protected继承,基类的protected变量在派生类中还是protected的。
q.InheritPrintBaseValue(); // ok ,
q.InheritPrintThoughBase(); //ok派生类的共有成员函数中访问基类的public,protected成员函数都是可以的,因为他们对于派生类来说是protected的
//q.PrintValue(); //error 不能访问基类的保护成员函数
return 0;
}
结果如下:
public:可以被1.该类中的函数、2.子类的函数、3.其友元函数访问,也可以由4.该类的对象访问。
注:友元函数包括3种:设为友元的普通的非成员函数;设为友元的其他类的成员函数;设为友元类中的所有成员函数。
第二:类的继承后方法属性变化。
private 属性不能够被继承。
使用private继承, 父类的protected和public属性在子类中变为private;
使用protected继承,父类的protected和public属性在子类中变为protected;
使用public继承, 父类的protected和public属性不发生改变;
如下所示:
public: protected: private:
public继承 public protected 不可用
protected继承 protected protected 不可用
private继承 private private 不可用
protected继承和private继承能降低访问权限。