Reading notes 2

xiaoxiao2021-03-06  121

About this pointer although this pointer is already very familiar, I discussed the question of this pointer here may haven't been noticed: In order to illustrate this property of this, I have self-written a simpler program, though Simple but specific: #include class a {public: a * p1; int m_data1; int m_data2; a () {m_data1 = 1; m_data2 = this-> m_data1; p1 = this;} void aa () {COUT << "A_AA" << Endl;} Virtual Void AAA () {cout << "A_AAA" << Endl;}}; Class B: Public a {public: int m_data1; int m_data3; b () {} Void print << m_data2 << Endl << m_data1 << endl;} Virtual void AAA () {cout << "b_aaa" << Endl;}}; void main ()}}; void main () {b b; b.print (); B.p1-> aa (); b.p1-> aaa (); b.p1-> m_data3 = 0; // Compile error ###} My problem is that the pointer P1 does not point to B itself? As soon as you look at the program, everyone knows: Not, the P1 pointer is a hidden parent class A to B. Yes, the answer is pair (if you also doubt this, you can only try it to the VC.), Here, I can also give an evidence directly, that is, the above compile, because A does not exist m_data3. Your answer actually shows a conclusion that I want to get 1, that is, this (in the program) pointer is pointing A. However, I want to ask that since P1 is the parent class to B, then B.P1-> AAA () should call that function? The answer is the one in B. If it is not a virtual function, the result is the one in A (this is known from the conclusion 1), it is a ghost that is a virtual function, but why? Although it seems to be like this, the P1 pointer does not end from beginning to end? Isn't a parent class pointing to the child's situation? Because there is no P1 = & B statement. :)

About the polymorphism and virtual function summarize as follows: 1) Pointer: The parent class can point to the subclass object, but can only call itself, the member function and the member variable, except for the virtual function; the pointer of the subclass can only point to the parent class The display type is converted into a subclass of objects, calling the sub-class itself, and the variable is except for the virtual function. 2) No pointer (type conversion between objects): The parent class object can be converted into a subclass object, and only its own functions and variables can not call the function and members of the subclass, regardless of the virtual function; The object cannot be displayed to the parent class object unless the person is written related code.

That is: The virtual function must be used with the pointer; except for the virtual function, the type conversion between the inheritance class has no direct effect.

Object survival

Four: Stack, Heap, Global, Local Static Production Method: First: In the function, main () is second: New method third: outside of any function range, initialization by startup code . The fourth: static objects within the range of functions

转载请注明原文地址:https://www.9cbs.com/read-98445.html

New Post(0)