C ++类或结构兼容性与C结构 [英] C++ Class or Struct compatiblity with C struct

查看:99
本文介绍了C ++类或结构兼容性与C结构的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

可以编写与C struct完全兼容的C ++类或结构。从兼容性我的意思是对象的大小和变量的内存位置。我知道它的邪恶使用 *(point *)& pnt 或甚至(float *)& pnt (在不同的情况下,变量是浮动),但认为它的真正需要的性能的缘故。

Is it possible to write a C++ class or struct that is fully compatible with C struct. From compatibility I mean size of the object and memory locations of the variables. I know that its evil to use *(point*)&pnt or even (float*)&pnt (on a different case where variables are floats) but consider that its really required for the performance sake. Its not logical to use regular type casting operator million times per second.

以这个例子

Class Point {
	long x,y;
	Point(long x, long y) {
		this->x=x;
		this->y=y;
	}

	float Distance(Point &point) {
		return ....;
	}
};

C版本是POD结构

struct point {
	long x,y;
};


推荐答案

是的。


  • 在两种语言中以相同的顺序使用相同的类型

  • 确保类中没有虚拟内容

  • 根据所使用的编译器,您可能需要调整结构打包(通常使用pragmas)以确保兼容性。

(编辑)


  • 此外,你必须小心检查sizeof()类型与您的编译器。例如,我遇到了一个编译器存储shorts作为32位值(当大多数将使用16)。更常见的情况是,int通常在32位架构上为32位,在64位架构上为64位。

这篇关于C ++类或结构兼容性与C结构的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆