Class can change the accessibility to it's content, but Struct can not.
And the default to class is private, and to Struct is Public.
This is just a memo and organization of what I've learned so far.
public means you can call or act on it from outside the class,
protected means you can call or act on it only from the class or the derived classes,
private means you can call or act on it only from the class.
1. Inheritance:
//By momo #include<iostream> using namespace std; class A{ public: int x; }; class B: public A{ public: int y; }x;
Using class XXX: xxxxx XXX, use the code above as an example, B inherit from A.
But what is Inherit??? It actually means that all the functions and variables in A can be used in B,
and that is why we call B inherit from A.
And when you use inheritance, use the code above as an example, it can rewrite as this:
//By momo #include<iostream> using namespace std; class B:{ public: int x; public: int y; }x;
they are both the same, you can taste a little bit about it.
2. Friendship:
If you are a friend with someone, you two share all the protected and private information with each other(only if you two are true friends)
//By momo #include<iostream> using namespace std; class A{ private: int x; friend class B; }a; class B{ public: int y; void prnt(A x){cout << x.x << endl;} }b;
Like this is OK, it won't give a compile error. And the friend statement can be written at anywhere in the class. But something like this is not OK,
//By momo #include<iostream> using namespace std; class A{ private: int x; }a; class B{ public: int y; friend class A; void prnt(A x){cout << x.x << endl;} }b;
It will give out a CE that says x is not accessible. The friend statement is only single way.
3. Constructor:
Just one thing to remember, constructor should always have it's accessibility turned to public.
//By momo #include<iostream> using namespace std; class A{ public: A(){ x = 1; } private: int x; }a;
------------------------------------------------------------------------------------------------------------
Class is such a fun thing, and I am told today that the array inside will be initialize, so convenient( from Yo Chiang )
沒有留言:
張貼留言