C++中,"SomeStruct"是结构,"member"是其成员,"&SomeStruct::member"是什么意思?

What does the "&SomeStruct::member" mean in C++ where "SomeStruct" is a struct and "member" is its member?

本文关键字:member SomeStruct 是什么 意思 成员 结构 C++      更新时间:2023-10-16

假设SomeStruct定义为:

struct SomeStruct {
    int member;
};

这些是什么意思?

  1. &SomeStruct::member
  2. int SomeStruct::*

我遇到这个,试图输出它的类型信息,但仍然不能弄清楚的含义。下面是一个工作示例:

#include <iostream>
#include <typeinfo>
using namespace std;
struct SomeStruct {
    int member;
};

int main(int argc, const char *argv[])
{
  cout << typeid(&SomeStruct::member).name() << endl;
  cout << typeid(int SomeStruct::*).name() << endl;
  return 0;
}

i686-apple-darwin10-gcc-4.2.1 (GCC) 4.2.1 (Apple Inc. build 5664)在我的MBP上编译,输出为:

M10SomeStructi
M10SomeStructi

int SomeStruct::*被称为"指向成员的指针",在本例中是指向SomeStruct成员的指针。严格来说,不是是指向成员函数的指针(尽管这是该语法最常用的用法)。

&SomeStruct::member是对SomeStruct成员member的引用。

参见相关问题

如果你想了解更多关于这个主题的完整信息,这里有一篇关于这个主题的不错的文章。

并且,c++ FAQ生活中关于该主题的强制性部分

这是指向成员函数/数据成员的指针语法。

int SomeStruct::*是指针的类型(指向SomeStructint数据成员的指针)。

&SomeStruct::member返回上述类型的指针

相关文章: