我应该同时使用头文件和 cpp/源文件吗?
我有一个 Mammal.h 文件,内容如下:
#ifndef MAMMAL_H
#define MAMMAL_H
class Mammal
{
public:
void Speak();
};
#endif
我的 CPP 文件如下所示:
#include "stdafx.h"
#include "Mammal.h"
#include <iostream>
void Mammal::Speak()
{
using namespace std;
cout << "Speaking";
}
我对此代码的使用如下所示:
#include "stdafx.h"
#include "Mammal.h"
int main()
{
Mammal *mammal = new Mammal();
mammal->Speak();
}
但是,我可以在头文件中执行此操作:
#include "stdafx.h"
#include <iostream>
#ifndef MAMMAL_H
#define MAMMAL_H
class Mammal
{
public:
void Speak()
{
using namespace std;
cout << "Speaking";
}
};
#endif
我还没有真正定义偏好......但我确实看到两者都有效。这两种方法有优点或缺点吗?
I have a Mammal.h file that reads:
#ifndef MAMMAL_H
#define MAMMAL_H
class Mammal
{
public:
void Speak();
};
#endif
My CPP file looks like:
#include "stdafx.h"
#include "Mammal.h"
#include <iostream>
void Mammal::Speak()
{
using namespace std;
cout << "Speaking";
}
And my use of this code is seen here:
#include "stdafx.h"
#include "Mammal.h"
int main()
{
Mammal *mammal = new Mammal();
mammal->Speak();
}
However, I could do this in the header file:
#include "stdafx.h"
#include <iostream>
#ifndef MAMMAL_H
#define MAMMAL_H
class Mammal
{
public:
void Speak()
{
using namespace std;
cout << "Speaking";
}
};
#endif
I haven't really defined a preference...but I do see that both work. Are there advantages or disadvantages to either of these approaches?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
尝试从多个地方调用该代码 - 因此 #include 多个源文件中的标头 - 您将在第二种方法中看到问题。如果同一函数有多个定义,即使它们是相同的,链接器也不喜欢这样做。
Try calling that code from more than one place -- and therefore #including the header in more than one source file -- and you'll see the problem in the second approach. The linker doesn't like it if you have more than one definition of the same function, even if they're identical.
Beta 是正确的,当头文件包含在多个文件中时,在头文件中定义函数会导致问题。
我还建议您将标头和实现分离到单独的文件中,作为良好的编码实践。头文件代表类的“接口”。公共函数是类的用户可以使用的函数,标头为人们提供了一种简洁的方式来查看函数,而不必关心实现。此外,这使您能够在不影响调用者的情况下更改实现,因为它们仅包含标头,并且实现通常只是链接的库。
Beta is correct that defining your functions in the header file will cause problems when your header is included in multiple files.
I would also suggest that you separate the header and implementation into separate files as just a good coding practice. The header file represents the "interface" of the class. The public functions are what are available to the users of the class, and the header provides a concise way for people to see the functions without having to care about the implementation. Also, this gives you the ability to change the implementation without affecting the callers, because they only include the header, and the implementation typically is just a library that gets linked in.