好吧,我正在用 C++ 制作文字冒险游戏,我对它还很陌生。我有 java 和其他一些语言的经验。但我有一个问题。我试图将主文件中的一个类调用到我的其他文件中,但出现错误。即使在我的头文件或 .cpp 文件中包含 main.cpp 时,我也会得到它。我已经知道将 .cpp 调用到另一个文件中是不好的做法,但由于 main 没有头文件,我不能完全包含它。
最佳答案
第一条规则;发布你的代码。代码本身是比您的描述更好的调试工具。无论如何...
I get it even when I include the main.cpp in my header file or in my .cpp file.
这是倒退的。您包括包含类定义的头文件在使用它们的文件中,而不是相反。所以……
// foo.h
#ifndef FOO_H
#define FOO_H
#include <string>
class foo {
public:
foo(const std::string& s);
void print_whatever() const;
private:
std::string _whatever;
};
#endif
//foo.cpp
#include <foo.h>
#include <iostream>
foo::foo(const std::string& s)
: _whatever(s) { }
void foo::print_whatever() const {
std::cout << _whatever;
}
//main.cpp
#include <foo.h>
int main() {
foo f("hola");
f.print_whatever();
}
关于c++ - 从其他文件调用 C++ 主类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12830346/