C++ 运算符 ->* 和 .*

C++ operator ->* and .*

美好的一天,

我在维基百科上看到 this question, but I'm specifically interested in the "object pointed to by member ..." type operators as listed here

我从未在实际代码的上下文中看到过这一点,因此这个概念对我来说似乎有些深奥。

我的直觉告诉他们应该按如下方式使用:

struct A
{
    int *p;
};

int main()
{
    {
        A *a = new A();
        a->p = new int(0);
        // if this did compile, how would it be different from *a->p=5; ??
        a->*p = 5;
    }

    {
        A a;
        a.p = new int(0);
        // if this did compile, how would it be different from *a.p=5; ??
        a.*p = 5;
    }

    return 0;
}

但这不会编译,因为 p 未声明。 (参见 example)

谁能提供一个在 C++ 中使用 operator->* and/or .* 的真实示例?

这些运算符用于指向成员对象的指针。您不会经常遇到它们。例如,它们可用于指定在 A 对象上运行的给定算法要使用的函数或成员数据。

基本语法:

#include <iostream>

struct A
{
    int i;
    int geti() {return i;}
    A():i{3}{}
};

int main()
{
    {
        A a;
        int A::*ai_ptr = &A::i; //pointer to member data
        std::cout << a.*ai_ptr; //access through p-t-m
    }

    {
        A* a = new A{};
        int (A::*ai_func)() = &A::geti; //pointer to member function
        std::cout << (a->*ai_func)(); //access through p-t-m-f
    }

    return 0;
}

->*.* 语法是 "pointer-to-member" 运算符,可用于存储指向特定对象成员的指针。

用法示例:

class A {
    public: int x;
};

int main() {
    A obj;
    int A::* memberPointer = &A::b;  //Pointer to b, which is int, which is member of A
    obj.*memberPointer = 42; //Set the value via an object

    A *objPtr = &obj;
    objPtr->*memberPointer = 21;  //Set the value via an object pointer
}