在头文件VS实现(.cpp)文件中定义构造函数 [英] Defining constructor in header file VS implementation (.cpp) file

查看:697
本文介绍了在头文件VS实现(.cpp)文件中定义构造函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

您好,感谢您的阅读。
这可能只是在个人偏好类别下,但无论如何我们去...

Hi there and thanks for reading. This might be just falling under the 'personal preferences' category but anyway here we go...

我可以定义一个类构造函数的主体类 .h 文件或实现文件 .cpp 中。这两种风格可能是相同的,只要编译器在一个特定的项目(项目对我意味着 dll )。
同样适用于任何成员函数:它们可以在头文件中定义,或者只是在那里声明,然后在cpp文件中定义。

I can define the body of a class constructor in the class .h file or in the implementation file .cpp. These two styles are probably identical as far as the compiler is concerned within a specific project (project for me means dll). Same applies to any member functions really: they can be defined in the header file or just declared there and then defined in the cpp file.

HOWEVER ...

HOWEVER...

我发现如果我需要包含这样的类头文件不同的项目(意味着最终使用头文件的代码最终在不同的 dll ),然后在头文件中的实际实现导致一些头痛在编译(不在链接...我don甚至达到这一点)。
为什么?好吧,我不会走得太多细节,但编译器显然试图解决所有可能在其他头文件等定义的功能...强迫穷人开始拉各种头文件eetc ...

I found that if I need to include such class header file(s) in different projects (meaning that ultimately the code that uses the header file ends up in a different dll) then having the actual implementation in the header file causes some headaches at compilation (not at linking... I don't even get to that point). Why? Well I won't go too much in detail but the compiler obviously tries to resolve all the functions which might be defined in other header files etc... forcing the poor developer to start pulling in various header files eetc...

LONGSTORY short:

L O N G S T O R Y short:

不是总是最好保持头文件没有任何实现,声明?这将使它更容易将它们包括在多个项目w / o不得不携带大量额外的垃圾。

Isn't it always best to keep header files free of any implementation and just use them for 'declarations'? That would make it easier to include them in more than one projects w/o having to carry around a lot of extra junk.

您对此有何看法?
谢谢!

What is your opinion about this? Thanks!

推荐答案

保持头文件没有实现,除非你想要实现内联/ setters)。除非他们是模板,当然。

Keep your headers free of implementations, unless you want the implementations to be inlined (e.g. trivial getters/setters). And unless they're templates, of course.

我没有理由对构造函数做出异常。将它们放在.cpp文件中。

I see no reason to make an exception for constructors. Put them in the .cpp file.

这篇关于在头文件VS实现(.cpp)文件中定义构造函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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