我有这个头文件的C + +应该使文件输入更容易编码,但我是它是有效的内存。
我有我的头文件中的类,看起来像这样:是否有可能#include在C++类中?
class FileInputOutput {
#include <fstream>
但我不知道这是否会包括像反正在顶部#include
语句,或者如果它只是包括它当班级被召唤时。
任何人都可以帮我吗?
我有这个头文件的C + +应该使文件输入更容易编码,但我是它是有效的内存。
我有我的头文件中的类,看起来像这样:是否有可能#include在C++类中?
class FileInputOutput {
#include <fstream>
但我不知道这是否会包括像反正在顶部#include
语句,或者如果它只是包括它当班级被召唤时。
任何人都可以帮我吗?
是否有可能#include在C++类中?
至于你的问题标题:这是可能的,是的。
尽管c(++)预处理器只是扩展了#include
'd文件中的文本,并且在编译的另一个阶段检查了C++验证,但您应该注意。
类似的代码
class FileInputOutput {
#include <fstream>
};
将注入类中的所有从fstream
文本。
这很可能不是你想要的。
只需使用类中的声明,fstream
做
#include <fstream>
class FileInputOutput {
std::fstream fs;
};
#include
只是在编译过程中由预处理器产生的包含文件内容复制/粘贴。 所以是的,当然,你可以做到这一点,但它并没有给你任何效率。就好像你已经将包含文件的内容直接内联写入包含文件中。
C++中的预处理器(和C中的)通过有效地将引用文件的文本复制到使用#include
语句的文件中来执行操作。
所以,当你写这样的代码:
Something.h
int my_rand() {
return 4; //chosen by dice roll, guaranteed to be fair
}
Main.cpp的
#include "Something.h"
int main() {
return my_rand();
}
正确编译前的最后文件开始看起来是这样的。
int my_rand() {
return 4; //chosen by dice roll, guaranteed to be fair
}
int main() {
return my_rand();
}
在你的情况,写东西像
class my_class {
#include<fstream>
/*...*/
};
,将导致一些非常奇怪的行为,并且将几乎肯定无法编译,因为<fstream>
的全部内容将被复制到中间的类,而且你写的课程不太适合这种写法,或者编写了<fstream>
来处理被注入不同的课程。
但是,在某些情况下,您可以在程序中间使用#include
。注意:
我Resource.txt
R"D(
Blah Blah Blah Blah Blah
)D"
Main.cpp的
int main() {
std::string blah_string = "" //The "" is unnecessary, but I use it to make Intellisense shut up
#include "My Resource.txt"
;
std::cout << blah_string << std::endl;
return 0;
}
这将正确打印出来
Blah Blah Blah Blah Blah
到控制台,因为它是一样的书写
int main() {
std::string blah_string =
R"D(
Blah Blah Blah Blah Blah
)D"
;
std::cout << blah_string << std::endl;
return 0;
}
这回答用户提供的问题包括:http://stackoverflow.com/questions/7347033/including-headers-inside-class-declaration-definition – NathanOliver
对于标准标题恕我直言,你应该只将它们包括在全球空间在标题的开头。 – NathanOliver
@NathanOliver本例使用标准标题。我很难想象在类定义中包含标准头文件的情况。 –