gpt4 book ai didi

c++ - 为什么 token 连接在 C++ 中不起作用?

转载 作者:行者123 更新时间:2023-11-28 00:01:26 29 4
gpt4 key购买 nike

我有以下代码,我想以编程方式访问结构的字段:

#include <stdio.h>
#include <stddef.h>

#define FIELD(NAME, NUM) {NAME##NUM}


struct SFOO
{
int i;
float f1;
float f2;
char c;
};

int main() {
printf("Offset of 'f1' is %u", offsetof(SFOO, f1));
printf("Offset of 'f1' is %u", offsetof(SFOO, FIELD(f, 1)));
}

main() 中的第一行有效,但第二行无法编译 (MSVC 2012)。如何使用 token 串联生成字段名称?

最佳答案

去掉 FIELD 定义中的 {}

#define FIELD(NAME, NUM)  NAME##NUM

根据您之前的定义,您的 print 语句将扩展为 offsetof 宏不会接受的内容:

    printf("Offset of 'f1' is %u", offsetof(SFOO, {f1}));

关于c++ - 为什么 token 连接在 C++ 中不起作用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38705670/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com