小编sup*_*oda的帖子

为什么不使用cpp文件包含类?

这个问题并不是重复" 为什么我不应该包含cpp文件而是使用标题? "而是更多的实践问题.

为了最好地构思这个问题,让我解释一下 在编写课程时,如果不是更多,它可以快速增长到几百行.出于可读性目的,我想基于每个方法将一个类分成单个文件.为了清楚起见,我并不是建议将整个项目变成一组包含,因为上面列出的帖子中提到的原因,而是将一个类分解为包含在他们自己的文件中的组件.

以下代码片段说明了我的意思

main.cpp中

#include <iostream>
#include "helloClass.h"
using namespace std;

int main()
 {
         hello a;
         cout<<a.out();
         cin.get();//just to pause execution
 }
Run Code Online (Sandbox Code Playgroud)

helloClass.h

#ifndef HELLOCLASS_H
#define HELLOCLASS_H
#include <string>
class hello
{
std::string  message;

public:
std::string out();
hello();
};

#endif
Run Code Online (Sandbox Code Playgroud)

helloClassMain.cpp

#include "helloClass.h"     
using namespace std;        
hello::hello()              
{                           
   message = "Hello World!";   
};                          

#include "helloClassOut.cpp"
Run Code Online (Sandbox Code Playgroud)

helloClassOut.cpp

string hello::out()
{                  
return message;    
}                  
Run Code Online (Sandbox Code Playgroud)

这将编译正常并按预期执行.当发生错误时我发现了一个额外的好处,因为编译器不仅会告诉你什么行,还会告诉你错误所在的文件.例如,我用未声明的变量编译它

$ c++ main.cpp helloClassMain.cpp -o hello
In file included from helloClassMain.cpp:8:0:
helloClassOut.cpp: In member …
Run Code Online (Sandbox Code Playgroud)

c++

5
推荐指数
1
解决办法
169
查看次数

标签 统计

c++ ×1