gpt4 book ai didi

c++ - 从 void 指针增加值

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

我正在尝试通过键盘快捷键修改一些变量[不需要来自同一个类/结构],比如:包含变量的 foo 结构:

struct Foo {
int a;
float b;
};

struct Foo2 {
int c;
};

还有一个主要的例子:

int main() {
Foo f;
Foo2 f2
void* p = &(f.a); //it could be &(f2.c)

if ('A' key activated) {
*p += 1;
}
}

目前,我卡在了这一点上:

error: invalid operands to binary expression ('void' and 'int')

让它工作的唯一方法是改变:

*p += 1;

通过:

*(int*)p += 1;

这不是一个好的解决方案,因为我不应该知道 p 指向的类型。有办法吗?

最佳答案

将指针转换为 void* 会丢失类型信息,编译器将不知道如何递增。你为什么不指向 Foo 呢?

int main() {
Foo f;
Foo* p = &f;

if ('A' key activated) {
p->a += 1;
}
}

另请记住,增加 float 不是一个好主意!

对于本回答评论中的问题:

struct FooBar
{
int *a;
float *b;
};

int main() {
Foo f;
Bar b;
FooBar fb{&f.a, &b.b};

if ('A' key activated) {
*(fb.a) += 1;
}
}

请注意,此解决方案是 C 风格的。查看 lethal-guitar 的答案以获得更 C++ 风格的解决方案。

关于c++ - 从 void 指针增加值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14419632/

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