c++ - 字段声明为 void/struct 或未在此范围内声明的变量

标签 c++

我一直在自学一些使用 SFML 的 OpenGL 来创建窗口/处理输入等。我的 main.cpp 开始变得有点笨拙,所以我决定开始拆分我的代码。我创建了一个 4X_vertex.h 和一个 4X_vertex.cpp(4X 是项目的名称)并将相关函数和结构从我的主文件中移到这些文件中。但是,当我编译时,出现错误

variable or field "drawVertexArray" declared void

根据我的研究,这似乎只是与下一个错误相关的无用信息,即

vertex was not declared in this scope

这是我的 main.cpp 中的包含列表:

#include <iostream>
#include <fstream>
#include <string>
#include <SFML/System.hpp>
#include <SFML/Window.hpp>
#include <SFML/Graphics.hpp>
#include "4x_vertex.h"
#include "4x_constants.h"

我的4X_vertex.h:

#ifndef _4X_VERT_H
#define _4X_VERT_H
struct vertex{
        GLfloat x,y,z;
        GLfloat r,g,b;
};
void drawVertexArray(vertex v[]);
vertex* loadVertexData();
#include "4X_vertex.cpp"
#endif

给我带来麻烦的 4X_vertex.cpp 部分:

using namespace std;

void drawVertexArray(vertex v[]){
    ... openGL stuff...
}

所有这些在我开始移动它之前都有效,所以我假设包含的内容或其他内容发生了一些奇怪的事情。非常感谢所有帮助!

最佳答案

只是一些提示。最佳做法是将您的项目分成多个源文件。通常,您会在主源文件的文件名中使用“main”一词(如果适用)。所以你可能有类似...

main.cpp
feature1.cpp
feature2.cpp
tools.cpp

对于您的其他文件,您通常会根据它们实现的类来命名它们。您通常会同时拥有 .h 和 .cpp。将您的声明放在 .h 中,而您在 .cpp 中的定义已使 .cpp 包含 .h。这可能会给你...

main.cpp
feature1.cpp    feature1.h
feature2.cpp    feature2.h
tools.cpp       tools.h

引用您的其中一个类的模块也包括它的 .h。所以,main.cpp 可能看起来像...

#include <iostream>
#include "feature1.h"
#include "feature2.h"

using namespace std;
void main(int argc, char **argv)
{ ...
    cout << "Done!\n";
}

feature1.cpp 可能是...

#include "feature1.h"
#include "tools.h"
feature1_class::feature1_class() { ... }
void feature1_class::AUsefulFeature(int val) { ... }
//etc.

...其中 feature1.h 声明了类、定义的常量等。f.g.,

#ifndef FEATURE1
#define FEATURE1
#include "tools.h"
class feature1_class
{
public:
    feature1_class();
    void AUsefulFeature(int val);
    int APublicMember;
};
#endif

您可能已经注意到 tools.h 实际上在 feature1.cpp 中包含了两次。它包含在 feature1.h 中并明确包含在 .cpp 文件中。如果您在 .h 文件中使用以下模式 ...

#ifndef TOOLS_H
#define TOOLS_H
//... do your thing
#endif

...那么多个包含不会给您带来任何问题。当您重构代码时,不必再担心清理问题。

如果到目前为止,您一直在为所有源代码使用单个文件,那么您可能一直在这样编译...

cl main.cpp

这会为您提供 .exe 和 .obj 以及其他文件。但涉及多个源文件时,并没有太大区别。你可以说...

cl main.cpp feature1.cpp feature2.cpp tools.cpp

还有很多东西需要学习,但这是一个开始,可以帮助您更好地组织编码思想。

关于c++ - 字段声明为 void/struct 或未在此范围内声明的变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11907574/

相关文章:

c++ - C++ 中的 Matlab 类型数组

c++ - 独立于语言环境的 "atof"?

c++ - 为什么在使用模板时会出现 "unresolved external symbol"错误?

c++ - 可以将模板参数用作字符串吗?

c++ - 将 C++ 库集成到 iPhone 应用程序中

c++ - Qml程序不运行

python - 通过 Python 将列表传递给 C++

c++ - 如何在 Linux 上从源代码安装 TBB 并使其工作

c++ - 在 C++ 中出现 "scope"错误

c++ - O(NlogN) 或 O(Nlog^2N) 中坐标值的 LIS