c++ - 从其他文件调用 C++ 主类

标签 c++

好吧,我正在用 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/

相关文章:

c++ - 如何在一个DLL中找到哪个进程加载了它?

c++ - 是否有返回字符的 ASCII 值的函数? (C++)

c++ - 如何从函数运算符(x,y)返回 vector 元素的引用

c++ - OpenCV matchTemplate minVal maxVal仅返回0和1

c++ - 3dsmax SDK c++ bonesdef.h

c++ - 在方法 c 中传递双指针

c++ - 使用 Functor 在集合中创建自定义排序方法

c++ - CV::MAT 在 Debug模式下预览图像

c++ - 4k * 4K float 的 mmap 导致段错误

c++ - 使用 shared_ptr 作为输出参数