C++中public,protected,private访问小结(转)
第一:private,public,protected方法的访问范围.
private: 只能由该类中的方法访问,不能被该类的对象访问. protected: 可以被该类中的方法和其友元函数访问,但不能被该类的对象访问 public: 可以被该类中的方法和其友元函数访问,也可以由该类的对象访问 第二:类的继承后方法属性变化: 使用private继承,父类的所有方法在子类中变为private; 使用protected继承,父类的protected和public方法在子类中变为protected,private方法不变; 使用public继承,父类中的方法属性不发生改变; |
但是我看到拷贝构造函数中,对象居然可以访问protected数据,why,哪里有资料?
Vector::Vector(Vector& vec)
{
cout<<vec.sz;
v = new int[sz=vec.sz];
memcpy((void*)v,(void*)vec.v,sz*sizeof(int));
}
类定义如下:
class Vector
{
public:
Vector(int);
~Vector(){ delete[]v; } //将堆中数组空间返还
Vector(Vector & );
int Size(){ return sz; }
void Display();
int& Elem(int); //返回向量元素
protected:
int* v; //指向一个数组,表示向量
int sz; //元素个数
};
再附一篇:
protected修饰类的成员有什么用?一直不是很明白,感觉和private差不多,就是可以被子类继承,但不能通过不同的object使用,只能由this或者friend来调用,同时又不能被用户。
IBM Linux Complier中的例子:
class A {
public:
protected:
int i;
};
class B : public A {
friend void f(A*, B*);
void g(A*);
};
void f(A* pa, B* pb) {
// pa->i = 1;
pb->i = 2;
// int A::* point_i = &A::i;
int A::* point_i2 = &B::i;
}
void B::g(A* pa) {
// pa->i = 1;
i = 2;
// int A::* point_i = &A::i;
int A::* point_i2 = &B::i;
}
C++ Gotchas上的解释: protected access requires not only that the function making the access be a member or friend of the derived class, but also that the object being accessed have the same type as the class of which the function is a member.
protected访问要求,访问函数为派生类的成员函数或友元函数,或者是被访问的对象同访问函数有相同的类型。