开发者

C++ -- what is operator .*?

In C++, you cannot overload operator .*开发者_StackOverflow中文版

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


This is a pointer to member operator.


It's the pointer-to-member dereference 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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜