About this pointer (Visitor mode)

xiaoxiao2021-03-06  43

See the Visitor design pattern two days ago, in which the classes that need to add functions should be added

Public Void Accept (Visitor V)

{

v.accept (this);

}

Even if this method has been implemented in the parent class, it has to be rewritten in the subclass.

It is estimated that the THIS parameter is estimated that today is trying to write.

Class Employee; Class Boss;

Class Visitor {public: Void Visit (Employee * e) {cout << "this is in employee visit << endl;}

Void Visit (boss * b) {cout << "this is in boss visit" << endl;}};

Class Employee {public: void accept (visitor v) {v.visit (this);}}

Class boss: public employee {public: // must rewrite // because each class involves the problem void accept (visitor v) {v.visit (this);}};

Void main () {visitor v; boss b; Employee E; B.Accept (v); E.Accept (v);

If the Accept method in the BOSS class is not overwritten, the result of the call output for the BOSS object is:

This is in employee visit

It can be seen that although the two objects are different, if the BOSS object calls the function of the parent class, the THIS pointer is used in the function.

The result is that the result is wrong because the THIS pointer used here is an Employee class.

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

New Post(0)