dot asterisk operator in c++

后端 未结 2 1054
长发绾君心
长发绾君心 2020-12-25 12:04

is there, and if, what it does?

.*
2条回答
  •  时光取名叫无心
    2020-12-25 12:24

    Yes, there is. It's the pointer-to-member operator for use with pointer-to-member types.

    E.g.

    struct A
    {
        int a;
        int b;
    };
    
    int main()
    {
        A obj;
        int A::* ptr_to_memb = &A::b;
    
        obj.*ptr_to_memb = 5;
    
        ptr_to_memb = &A::a;
    
        obj.*ptr_to_memb = 7;
    
        // Both members of obj are now assigned
    }
    

    Here, A is a struct and ptr_to_memb is a pointer to int member of A. The .* combines an A instance with a pointer to member to form an lvalue expression referring to the appropriate member of the given A instance obj.

    Pointer to members can be pointers to data members or to function members and will even 'do the right thing' for virtual function members.

    E.g. this program output f(d) = 1

    struct Base
    {
        virtual int DoSomething()
        {
            return 0;
        }
    };
    
    int f(Base& b)
    {
        int (Base::*f)() = &Base::DoSomething;
        return (b.*f)();
    }
    
    struct Derived : Base
    {
        virtual int DoSomething()
        {
            return 1;
        }
    };
    
    #include 
    #include 
    
    int main()
    {
        Derived d;
        std::cout << "f(d) = " << f(d) << '\n';
        return 0;
    }
    

提交回复
热议问题