Класс C++ или совместимость Структуры со структурой C

Вот плагин jQuery для установки высот нескольких отделений, чтобы быть тем же. И ниже фактический код плагина.

$.fn.equalHeights = function(px) {
$(this).each(function(){
var currentTallest = 0;
$(this).children().each(function(i){
    if ($(this).height() > currentTallest) { currentTallest = $(this).height(); }
        });
    if (!px || !Number.prototype.pxToEm) currentTallest = currentTallest.pxToEm(); //use ems unless px is specified
        // for ie6, set height since min-height isn't supported
    if ($.browser.msie && $.browser.version == 6.0) { $(this).children().css({'height': currentTallest}); }
        $(this).children().css({'min-height': currentTallest}); 
    });
    return this;
};

6
задан Cem Kalyoncu 15 September 2009 в 22:55
поделиться

7 ответов

Yes.

  • Use the same types in the same order in both languages
  • Make sure the class doesn't have anything virtual in it (so you don't get a vtable pointer stuck on the front)
  • Depending on the compilers used you may need to adjust the structure packing (usually with pragmas) to ensure compatibility.

(edit)

  • Also, you must take care to check the sizeof() the types with your compilers. For example, I've encountered a compiler that stored shorts as 32 bit values (when most will use 16). A more common case is that an int will usually be 32 bits on a 32-bit architecture and 64 bits on a 64-bit architecture.
9
ответ дан 8 December 2019 в 02:40
поделиться

Самым чистым было сделать это, чтобы наследовать из структуры C:

struct point
{
    long x, y;
};

class Point : public struct point
{
  public:
    Point(long x, long y)
        {    this->x=x; this->y=y; }

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

Компилятор C ++ гарантирует, что точка структуры стиля C имеет тот же макет, что и у компилятора C. Класс C ++ Point наследует этот макет для своей части базового класса (и, поскольку он не добавляет данных или виртуальных членов, он будет иметь тот же макет). Указатель на класс Point будет преобразован в указатель на точку структуры без приведения, поскольку преобразование в указатель базового класса всегда поддерживается. Таким образом, вы можете использовать объекты класса Point и свободно передавать указатели на них функциям C, ожидая указателя на точку структуры.

Конечно, если уже существует файл заголовка C, определяющий точку структуры,

20
ответ дан 8 December 2019 в 02:40
поделиться

POD applies to C++. You can have member functions. "A POD type in C++ is an aggregate class that contains only POD types as members, has no user-defined destructor, no user-defined copy assignment operator, and no nonstatic members of pointer-to-member type"

You should design your POD data structures so they have natural alignment, and then they can be passed between programs created by different compilers on different architectures. Natural alignment is where the memory offset of any member is divisible by the size of that member. IE: a float is located at an address that is divisible by 4, a double is on an address divisible by 8. If you declare a char followed by a float, most architectures will pad 3 bytes, but some could conceivably pad 1 byte. If you declare a float followed by a char, all compilers (I ought to add a source for this claim, sorry) will not pad at all.

5
ответ дан 8 December 2019 в 02:40
поделиться

C and C++ are different languages but it has always been the C++'s intention that you can have an implementation that supports both languages in a binary compatible fashion. Because they are different languages it is always a compiler implementation detail whether this is actually supported. Typically vendors who supply both a C and C++ compiler (or a single compiler with two modes) do support full compatibility for passing POD-structs (and pointers to POD-structs) between C++ code and C code.

Often, merely having a user-defined constructor breaks the guarantee although sometimes you can pass a pointer to such an object to a C function expecting a pointer to a struct with and identical data structure and it will work.

In short: check your compiler documentation.

1
ответ дан 8 December 2019 в 02:40
поделиться

Use the same "struct" in both C and C++. If you want to add methods in the C++ implementation, you can inherit the struct and the size should be the same as long as you don't add data members or virtual functions.

Be aware that if you have an empty struct or data members that are empty structs, they are different sizes in C and C++. In C, sizeof(empty-struct) == 0 although in C99, empty-structs are not supposed to be allowed (but may be supported anyway as a "compiler extension"). In C++, sizeof(empty-struct) != 0 (typical value is 1).

1
ответ дан 8 December 2019 в 02:40
поделиться

В дополнение к другим ответам я бы не стал помещать какие-либо спецификаторы доступа (public :, private: etc) в ваш класс / структуру C ++. IIRC компилятору разрешено переупорядочивать блоки переменных-членов в соответствии с видимостью, так что private: int a; pubic: int b; может поменять местами a и b. См., Например, эту ссылку: http://www.embedded.com/design/218600150?printable=true
Я признаю, что сбит с толку, почему определение POD не включает запрет на этот эффект.

0
ответ дан 8 December 2019 в 02:40
поделиться

As long as your class doesn't exhibit some advanced traits of its kind, like growing something virtual, it should be pretty much the same struct.

Besides, you can change Class (which is invalid due to capitalization, anyway) to struct without doing any harm. Except for the members will turn public (they are private now).

But now that I think of your talking about type conversion… There's no way you can turn float into long representing the same value or vice versa by casting pointer type. I hope you only want it these pointers for the sake of moving stuff around.

-2
ответ дан 8 December 2019 в 02:40
поделиться
Другие вопросы по тегам:

Похожие вопросы: