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

nam*_*ero 0 c++ operators dereference member-access

美好的一天,

我已经遇到这个问题,但我特别感兴趣的是"指向的对象成员..."作为上市型运营商在这里维基百科.

我从未在实际代码的上下文中看到过这个,所以这个概念对我来说有些深奥.

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

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;
}
Run Code Online (Sandbox Code Playgroud)

但这不会编译因为p未声明.(见例)

任何人都可以提供一个在C++中使用operator - >*和/或.*的真实示例吗?

Tar*_*ama 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;
}
Run Code Online (Sandbox Code Playgroud)