Esoteric C++ operators

前端 未结 6 497
渐次进展
渐次进展 2020-12-28 08:37

What is the purpose of the following esoteric C++ operators?

Pointer to member

::*

Bind pointer to member by pointer



        
6条回答
  •  慢半拍i
    慢半拍i (楼主)
    2020-12-28 09:13

    A pointer to a member allows you to have a pointer that is relative to a specific class.

    So, let's say you have a contact class with multiple phone numbers.

    class contact
    {
        phonenumber office;
        phonenumber home;
        phonenumber cell;
    };
    

    The idea is if you have an algorithm that needs to use a phone number but the decision of which phone number should be done outside the algorithm, pointers to member solve the problem:

    void robocall(phonenumber contact::*number, ...);
    

    Now the caller of robocall can decide which type of phonenumber to use:

    robocall(&contact::home, ...);    // call home numbers
    robocall(&contact::office, ...);  // call office number
    

    .* and ->* come into play once you have a pointer. So inside robocall, you would do:

    contact c = ...;
    c.*number;    // gets the appropriate phone number of the object
    

    or:

    contact *pc = ...;
    pc->*number;
    

提交回复
热议问题