1、类成员函数可以访问类内:private+protected+public
2、类对象可以访问类内: public (protected+private不可)
3、派生类成员函数可以访问父类内:protected+public (private不可)
4、派生类对象可以访问: public (protected+private不可)
5、总结:private和protected类之间的区别只有在基类派生的类中才会体现出来,派生类的成员可以直接访问基类的protected成员,但不能直接访问基类的private成员。对于外部世界,protected成员与private成员相似;对派生类来说,protected成员与public成员相似。
6、各类派生例程:
#include <iostream>
using namespace std;
class Base{
private:
int a1;
protected:
int a2;
public:
int a3;
Base()
{
a1=1;a2=2;a3=3;
}
};
class child1 : public Base
{
public:
child1():Base(){}
void func()
{
//cout << a1 << endl; //private wrong!
cout << a2 << endl; //protected
cout << a3 << endl; //public
}
};
class child2 : protected Base
{
public:
child2():Base(){}
void func()
{
//cout << a1 << endl; //private wrong!
cout << a2 << endl; //protected
cout << a3 << endl; //protected
}
};
class child3 : private Base
{
public:
child3():Base(){}
void func()
{
//cout << a1 << endl; //private wrong!
cout << a2 << endl; //private ,can be used by child class
cout << a3 << endl; //private ,can be used by child class
}
};
int main()
{
child1 child;
//cout << child.a1 << endl; //private
//cout << child.a2 << endl; //protected wrong!
cout << child.a3 << endl; //public
child2 _child;
//cout << _child.a1 << endl; //private
//cout << _child.a2 << endl; //protected wrong!
//cout << _child.a3 << endl; //protected wrong!
child3 __child;
//cout << __child.a1 << endl; //private
//cout << __child.a2 << endl; //private wrong!
//cout << __child.a3 << endl; //private wrong!
return 0;
}