gpt4 book ai didi

c++ - 如何测试结构的成员是否已定义 (c++)

转载 作者:太空狗 更新时间:2023-10-29 20:01:54 24 4
gpt4 key购买 nike

<分区>

我正在尝试测试在调用函数之前是否定义了声明为指向 void 的指针的结构成员。但是,似乎每当我向基本程序添加任何额外内容(例如末尾的 std::cout)时,“testB”总是等于 true。我无法更改“struct a”的声明方式,因为它是外部库的一部分。

那么,我该如何测试声明为 void 指针的结构成员实际上是否使用正确的类型定义?

示例结构

struct b { };

struct a {
void *b;
};

我正在尝试测试的示例代码

struct a myA;
struct b myB;
myA.b = &myB;
foo(myA);

失败的示例测试程序

#include <iostream>

int main() {

struct a aa;
struct b bb;
// the following line is commented out so I'm expecting 'testB' to evaluate to false
// aa.b = &bb;

struct b *testB = static_cast<struct b*>(aa.b);

if(testB) {
std::cout << "is defined" << std::endl;
} else {
std::cout << "is not defined" << std::endl;
}

std::cout << "why does adding this line out result in testB equating to true" << std::endl;

return 0;
}

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