【发布时间】:2016-02-16 14:40:54
【问题描述】:
我在Main.cpp 文件中定义了函数int getRandomNumber()。在这个文件之外,还有类,由头文件和类文件组成。
函数int getRandomNumber()由于某种原因不能从其他类文件中访问,即使它被认为是全局的。
Main.cpp 中的代码如下所示:
#include <iostream>
using namespace std;
int getRandomNumber() {
return 4; // Chosen by fair dice roll
}
#include "folder/ClassName.h"
int main(int argc, char* argv[]) {
ClassName t;
t.test();
return 0;
}
ClassName.h 的内部看起来像这样:
#ifndef SRC_CLASSNAME_H_
#define SRC_CLASSNAME_H_
class ClassName {
public:
ClassName();
virtual ~ClassName();
void test();
};
#endif /* SRC_CLASSNAME_H_ */
最后,ClassName.cpp 的内部包含以下内容:
#include <iostream>
#include "ClassName.h"
using namespace std;
ClassName::ClassName() {
cout << "Created" << endl;
}
ClassName::~ClassName() {
cout << "Destroyed" << endl;
}
void ClassName::test() {
cout << "Tested" << endl;
}
为什么“Created”、“Tested”和“Destroyed”都打印到控制台,即使ClassName.cpp文件从未明确包含在任何地方?
为什么不能从ClassName.h 文件中访问int getRandomNumber(),即使预处理器将它粘贴到包含它的位置?同样的事情也适用于<iostream>。为什么需要在.cpp 文件中再次包含它?
【问题讨论】:
-
似乎
ClassName.cpp文件在项目中,因此它与程序的其余部分一起构建。而且您无法从头文件(或任何其他源文件)访问getRandomNumber,因为它没有在其他任何地方声明。 -
您需要将
getRandomNumber()移动到标题中,然后将该标题包含在ClassName.h中以便您使用它,但仍保留Main.cpp文件中的功能。而且我认为您将标头与源文件(c,cpp)混淆了,编译器将每个源文件视为一个单独的文件,因此您需要在两个 cpp 文件中包含iostream。 -
哦,我现在明白这个概念了。谢谢你们俩!因此,在头文件中,您声明 内容,然后在
.cpp文件中放入内容,可以从仅包含头文件的任何其他源文件中访问这些内容。这个问题我该怎么办?
标签: c++ eclipse include eclipse-mars