强制转换为使用typedef创建的结构类型

Casting to struct type created with typedef

本文关键字:创建 结构 类型 typedef 转换      更新时间:2023-10-16

我的C++代码中的结构存在强制转换问题。我使用C型铸造。但是,如果我尝试使用替代名称(使用typedef创建)进行强制转换,我会出现错误。请看我的代码。

class T
{
public:
typedef struct kIdS* kIdN;
typedef struct kIdS {
int* a;
double* b;
}  kIdR;
typedef struct tIdS {
int* a;
double* b;
float* c;
}  tIdR;
int a;
double b;
float c;
void F()
{
a = 0; 
b = 0; 
c = 0;
struct kIdS A = {&a, &b};
struct tIdS B = {&a, &b, &c};
struct kIdS* knv[] = {&A, (struct kIdS*)&B};
struct kIdS* knv1[] = {&A, (kIdN)&B}; //error
}
};

错误为:

error C2440: 'initializing' : cannot convert from 'T::kIdN' to 'T::kIdS *'
Types pointed to are unrelated; conversion requires reinterpret_cast, 
C-style cast or function-style cast

为什么我不能使用替代名称?如何使用typedef创建的替代名称来解决此问题?

为什么不使用继承?

struct tIdS : public kIdS { ... }

错误的原因是在第一个typedef struct kIdS* kIdN中,您的类中没有名为kIdS的结构,所以C++编译器认为您谈论的是全局struct kIdS,然后是typedef,该全局结构到kIdN,在第struct kIdS* knv1[] = {&A, (kIdN)&B};行中,错误很明显,全局struct kIdS*不能代替T::kIdS*,但我有一个问题要问您,为什么你使用struct X,而你可以简单地说X??

我会去掉过多的typedef。

struct kIdS {
int* a;
double* b;
};
typedef kIdS* kIdN;
typedef kIdS kIdR;
.....
kIdS* knv[] = {&A, (kIdS*)&B};
kIdS* knv1[] = {&A, (kIdN)&B};