简体   繁体   中英

C++ — what is operator .*?

In C++, you cannot overload operator .*

Can someone give me an example for the usage of operator .* ?

这是一个指向成员运算符的指针

Simple Example:

class Action
{
    public:
        void yes(std::string const& q) { std::cout << q << " YES\n"; }
        void no(std::string const& q)  { std::cout << q << " NO\n"; }
};

int main(int argc, char* argv[])
{
    typedef void (Action::*ActionMethod)(std::string const&);
                       //  ^^^^^^^^^^^^  The name created by the typedef
                       // Its a pointer to a method on `Action` that returns void
                       // and takes a one parameter; a string by const reference.

    ActionMethod method = (argc > 2) ? &Action::yes : &Action::no;
    Action  action;

    (action.*method)("Are there 2 or more parameters?");
     //  ^^^^^^ Here is the usage.
     //  Calling a method specified by the variable `method`
     // which points at a method from Action (see the typedef above)
}

As a side note. I am so glad you can not overload this operator. :-)

This is the operator used when using pointers to member variables. See here .

.* dereferences pointers to class members. when you need to call a function, or access a value that is containing within another class, it must be referenced, and a pointer is created in that process, which also needs to be removed. the .* operator does that.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM