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

时间:2015-07-01 10:47:59

标签: c++ operators dereference member-access

美好的一天,

我遇到了this个问题,但我对维基百科上列出的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-> *和/或。*的真实示例吗?

2 个答案:

答案 0 :(得分:6)

这些运算符用于指向成员对象。你经常不会碰到它们。例如,它们可用于指定对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;
}

答案 1 :(得分:0)

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

用法示例:

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
}