强制转换为使用typedef创建的结构类型
Casting to struct type created with typedef
我的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};
相关文章:
- 创建结构的数组时遇到分段错误
- 如何在 c++ 中创建结构向量的映射
- 为什么我们再次从结构对象创建结构变量?
- 如何在C++中为堆栈动态创建结构?
- 如何创建结构的结构结构,等等嵌套多个结构?
- 创建结构作为枚举类成员
- 第一次尝试使用new动态创建结构数组,程序挂起没有错误
- 创建结构体向量,表达式:向量下标超出范围
- variadic宏来创建结构
- C++类中创建结构的向量
- 如何动态创建 C++ 结构
- 如何在C++循环中创建结构成员
- 如何读取文件中的数据并创建结构向量
- C++从 DLL 创建结构
- 动态数组添加元素而不创建结构变量/对象
- 创建结构并传递IT功能
- c ++ 当我创建结构数组时,如何使用结构数组内的类的参数调用构造函数
- 尝试创建结构对象,在位置0x3FE00000中创建访问冲突写入错误
- 如何创建结构类型数组的地图对象
- 在C 中创建结构数组