C++中public,protected,private访问小结(转)

本文详细解析了C++中public、protected和private访问控制符的作用及区别,特别针对protected成员的访问权限进行了深入探讨,并通过具体代码示例展示了拷贝构造函数如何能够访问protected成员变量。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

 
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访问要求,访问函数为派生类的成员函数或友元函数,或者是被访问的对象同访问函数有相同的类型。

 
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值