Https://class.coursera.org/pkupop-001/forum/thread? Thread_id = 350 Guo Tiankui · 6 months ago in the courseware, we know that the following program cannot be compiled:
class A{protected:int x;};class B:A{void foo(){A a;a.x=1;}};
The reason is that X is protected, so the variable of the object of a cannot be accessed in Class B.
However, the following program can be compiled:
class A{protected:int x;};class B:A{void foo(){B a;a.x=1;}};
This is very intuitive, isn't it? It is clear that a is the base class of B, and the permission should be larger than B, but instead, Class B is required.
And because the two objects belong to the same class, they can access each other's private/protected variables, this is like "feeding you how to tamper with my personal items" "because we are in the same class." It's not intuitive at all ......
It is said that the same is true for Java. Why is it designed like this? Is there any convincing explanation? 0 votes received. · flag Ge Yu · 6 months ago
For a single class, protected and private are the same.
0 votes encoded ed. · flag + comment Shi haoyue · 6 months ago asked a similar question. Why is C ++ designed to allow internal member functions of a class to access private members of all such variables? Why is it unscientific ...... Just like the following <overload.
class A {
public:
bool operator < (const A& o) const {
return a < o.a;
}
private:
int a;
}
0 votes encoded ed. · flag + comment Guo wenhan · 6 months ago
If foo is put out, can it be compiled? Is it a compiler bug?
Or is it possible that the design is based on Shi's saying?
0 votes received. · flag + comment Guo Wei instructor · 6 months ago. I don't know what's going on yet. 0 votes encoded ed. · flag Guo Tiankui · 6 months ago (catch 0 votes encoded ed. · In the flag Jiaying Liu/Liu jijia instructor · 6 months ago C ++, class access permissions are for classes, not for objects. The access permission is only valid for the compiler during compilation. 0 votes encoded ed. · flag Guo wenhan · 6 months ago does not understand the problem of Miss Liu. I think it should be for objects. Class myclass; Is myclass a unable to access private members of myclass B? 0 votes encoded ed. · flag + comment anonymous · 6 months ago. in Foo (), X tries to access the protected member X of a local variable A through the public interface of Class A. Naturally, it won't work.
B. in Foo (), X tries to access X through the private interface of Class B (because Foo () is a member function of Class B) and the Public inheritance of Class, naturally, it is allowed.
Of course, C ++ has too many abnormal designs. This is not exactly the case. If you are interested, visit this website.
Http://www.yosefk.com/c++fqa/
About how a derived class accesses the protection variables of base class objects -- Coursera