c++关于protected成员的访问问题 #include <iostream>
using namespace std;
class B{
protected:
int test = 0;
public:
void get(int& i) {
i = test;
}
void set(int i) {
test = i;
}
void fun(B& b) {
test = b.test;//这里为什么可以直接访问?
};
};
int main() {
B b1;
b1.set(10);
B b2;
b2.fun(b1);
int temp=0;
b2.get(temp);
cout << temp<<endl;
system("pause");
return 0;
}
编译后b2的test 的值是10,但在fun()中是直接访问b1的test成员 为什么没有出错? ------解决思路---------------------- 因为fun()是B类的成员函数,成员函数可以访问该类的所有成员变量。 ------解决思路----------------------
你为什么认为不能,test 是他自己的成员能访问有什么问题么? ------解决思路---------------------- protected
C++ Specific —>
protected: [member-list]
protected base-class
When preceding a list of class members, the protected keyword specifies that those members are accessible only from member functions and friends of the class and its derived classes. This applies to all members declared up to the next access specifier or the end of the class.
When preceding the name of a base class, the protected keyword specifies that the public and protected members of the base class are protected members of the derived class.
Default access of members in a class is private. Default access of members in a structure or union is public.
Default access of a base class is private for classes and public for structures. Unions cannot have base classes.
For related information, see public, private, friend, and Table of Member Access Privileges.
END C++ Specific
Example
// Example of the protected keyword
class BaseClass
{
protected:
int protectFunc();
};
class DerivedClass : public BaseClass
{
public:
int useProtect()
{ protectFunc(); } // protectFunc accessible
// from derived class
};
void main()
{
BaseClass aBase;
DerivedClass aDerived;
aBase.protectFunc(); // Error: protectFunc not
// accessible
aDerived.protectFunc(); // Error: protectFunc not
// accessible in derived class
}