我有以下代码:
#include <iostream>
#include <string>
using namespace std;
struct foo_s {
string a;
string b;
string c;
};
void print_field(foo_s* foo, string foo_s::* field) {
cout << "field: " << field << " - " << foo->*field << endl;
}
int main() {
foo_s my_foo = {
"a",
"b",
"c",
};
print_field(&my_foo, &foo_s::a);
print_field(&my_foo, &foo_s::b);
print_field(&my_foo, &foo_s::c);
return 0;
}
它的输出为:
field: 1 - a
field: 1 - b
field: 1 - c
我对于 print_field()
函数中的具体细节有些困惑,主要表现为:
field
的类型是什么?我猜它应该是指向字符串 foo_s 成员的指针
- 为什么
field
的值总是相同的(本例中为1),而foo->*field
却得到不同的结果?
主要困惑于第二点。我原以为 field
是从结构体开头的“偏移量”,而 foo->*field
则类似于以下概念等效的内容:
char* ptr = static_cast<char*>(foo);
ptrdiff_t offset = somehow_get_the_byte_offset_from_pointer_to_member(field);
ptr = ptr[offset];
string result = *static_cast<string*>(ptr);
但似乎行不通,因为field
的值在调用中没有变化。我错过了什么?标准具体描述了这个操作的方式是什么?
static_cast
触发了编译时错误,我应该明白这是怎么回事。 - anthonyvd