C++返回指向成员的指针

标签 c++

“指向成员的指针”返回类型的语法是什么?

struct Point {
    int x;
    int y;
    int z;
};

// compiles
decltype(&Point::x) getX () {
   return &Point::x;
}

// does not compile... how to do this without decltype?
int (Point::*) getX () {
   return &Point::x;
}


// Use case:
Point p, q;
auto pm = getX();
p.*pm = 1;  // p.x = 1
q.*pm = 2;  // q.x = 2

最佳答案

你不需要括号:

int Point::* getX () {
   return &Point::x;
}

想象一下将括号与常规指针一起使用:

int (*) getX() // compiler says WTF
{
   static int x; 
   return &x;
}

关于C++返回指向成员的指针,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24917238/

相关文章:

c++ - 是否有用于旋转操作的 C++ 函数?

C++ 模板正式排序规则

c++ - 两次 GCC 编译相同的输入,生成两个不同的代码(第二个错误)

c# - 通过 CLI 将 fstream(或等价物)从 C# 传递到 C++

c++ - enable_if 和转换运算符?

c++ - 有没有办法让 QXmlStreamReader 处理格式错误的 XML?

c++ - 在 C++ 中使用公共(public)函数返回类指针

c++ - 检测字符串和常量字符数组的代码

C++ 和 Qt - 从页面内容编码

android - 如何防止 Gradle/Android Studio 覆盖 CMake 提供的 C++ 编译器设置?