向前声明为struct vs类 [英] Forward declaration as struct vs class

查看:434
本文介绍了向前声明为struct vs类的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在类的C ++前向声明中发现一个错误,该声明被错误地声明为 struct Book 而不是 class Book 。我认为Book曾经是一个结构,被更改为一个类,但仍保留了前向声明。


Book.h:

  class Book {
...
};

Library.h:

  struct书; 

类库{
std :: vector< Book *>图书;
};

没有编译器警告,生成的程序似乎运行正常。这让我感到好奇:从理论上讲,这会引起问题吗?这只是一个指针,是的,但是例如,如果该类具有虚方法,多重继承,则指针是否可以不同? / p>

我知道类/结构之间关于默认公共/私有之间的区别,但是我要特别询问正向声明和交换它们的可能后果。


UPDATE 较新版本的Xcode现在在出现不匹配时发出此警告:

  Struct'Book'先前被声明为一类;这是有效的,但可能会导致Microsoft C ++ ABI 


解决方案

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



必须在<$ c $上使用 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

这篇关于向前声明为struct vs类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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