且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

向前声明为struct vs类

更新时间:2022-10-17 13:26:20

就前向声明而言,>

struct class 是完全可互换的。即使是定义,它们也只影响对象成员的默认访问说明符,其他所有内容都是等效的。您总是定义对象的类。



必须在 struct 的唯一位置c> class ,是在向前声明绑定。






关于您的编辑:


我知道类/结构在默认的public / private之间的区别,但我在特别询问前向声明以及交换它们的可能后果。


Visual C ++产生警告 C4099 。这样做是因为其功能的名称修饰包含了您使用的关键字。因此,程序 可能无法正确链接。因此,使用VC ++时,可能无法链接完全符合标准的代码(这是微软的重要举措,AFAIC)。



对此警告的讨论以及为什么可以这样做如果您受到纪律处分,则可以忽略它,可以找到此处


I found a mistake in a C++ forward declaration of a class, which was wrongly declared as struct Book instead of class Book. I think Book used to be a struct, got changed to a class but the forward declarations remained.

Book.h:

class Book {
    ...
};

Library.h:

struct Book;

class Library {
    std::vector<Book*> books;
};

There were no compiler warnings and the resulting program seemed to work fine. It made me curious: in theory, can this ever cause a problem? It's just a pointer, yes, but for example, if the class had virtual methods, multiple inheritance, could the pointers be different?

I know the differences between class/struct regarding default public/private but I'm asking specifically about the forward declarations and possible consequences of swapping them.

UPDATE newer versions of Xcode now give this warning when there's a mismatch:

Struct 'Book' was previously declared as a class; this is valid, but may result in linker errors under the Microsoft C++ ABI

struct and class are completely interchangeable as far as forward declarations are concerned. Even for definitions, they only affect the default access specifier of the objects members, everything else is equivalent. You always define "classes" of objects.

The only place where struct must be used over class, is when forward declaring opaque data for bindings.


Regarding your edit:

I know the differences between class/struct regarding default public/private but I'm asking specifically about the forward declarations and possible consequences of swapping them.

Visual C++ produces warning C4099. It does it, because the name decoration for its functions incorporates the keyword you used. Therefore, programs may fail to link properly. So perfectly standard compliant code may not link when using VC++ (A bonehead move on Microsoft's part, AFAIC).

A discussion of this warning, as well as why it can be ignored if you are disciplined, can be found here