gpt4 book ai didi

C++ 结构问题

转载 作者:太空狗 更新时间:2023-10-29 23:26:26 25 4
gpt4 key购买 nike

我是一名正在尝试学习 C++ 的 Java 开发人员。 C++ 的多文件结构对我来说很奇怪,作为一个 Java 开发人员,被类宠坏了。

我正在尝试制作一个可以加载其他 .cpp 文件的 .cpp 文件,类似于加载其他类的 Java 类。我的理解是,我有 3 个文件:main.cpp、filetobeloaded.h 和 filetobeloaded.cpp 都在同一个目录中。 main.cpp 将有一个

#include <filetobeloaded.h>

然后filetobeloaded.h会有

#ifndef LOOP_H
#define LOOP_H

void loop_start();
void loop_run();
void loop_init();

#endif /* LOOP_H */

虽然 filetobeloaded.cpp 会有

void loop_init(){
//load libraries here
}

void loop_start(){
//this loop runs as long as the user doesn't request the program to close.
//In that case, this function will return and the program will exit.
}

void loop_run(){
//render stuff here, call subroutines
}

显然,我做错了什么,因为我的编译器告诉我该行

#include <filetobeloaded.h>

无效,因为文件不存在。我已经检查过,filetobeloaded.h 和 filetobeloaded.cpp 都在与 main.cpp 相同的目录中。我不知道为什么会搞砸。

问题:

  1. 为什么会出现错误,我该如何解决?

  2. 有没有比我现在做的更好的方法将我的源代码划分到不同的文件?

  3. 您能否以 Java 开发人员能够理解的方式解释 C++ 多文件结构?

我正在尝试使用 OGL 在 C++ 中制作游戏。我正在学习 C++ 与 Java,因为速度更快、内存泄漏更少(我希望如此)以及 Steam 集成。

我没有一本关于 C++ 的好书,我在网上搜索了很多...每个人似乎都有不同的方法来做这件事,这让我很困惑...

最佳答案

  1. 正在做 #include <...>在 include 目录中搜索(特定于编译器,通常是 /usr/include 和一些其他用于 Linux 的目录,或 Windows 上的编译器安装目录),而 #include "..."搜索当前目录。确保使用正确的。

  2. 不,你做对了。

  3. 在C++中,有声明1和定义2。声明可以在任何地方,并且在一个翻译单元中可以有任意多的同名声明,但是(非 inline ,非模板,非内部链接)定义只能在大多数.cpp文件(技术上称为“编译单元”或“翻译单元”),否则您将在链接时收到“多重定义”错误。还值得注意的是,定义也可以用作声明,但反之则不然。

    在 C++ 中,您不能像在 Java 中那样在声明之前使用名称(函数、结构、变量等),但您可以在定义之前使用它 在大多数情况下,只需将声明写在使用点之上。

    头文件只是让您在所有需要它们的文件中放置声明(和 inline 函数定义和模板定义),而不必在每个 .cpp 文件中一遍又一遍地复制和粘贴它们。实际上,您完全可以在不使用头文件的情况下编写 C++,但这会非常乏味,并且会出现大量代码重复。

1 不是定义的声明示例:

extern bool bar;
class c;
int foo();
int foo();
int foo(); // Can have many declarations of the same name as long as they match

2 定义示例(也是声明):

bool bar;
bool baz = false;
class c { int m; };
int foo() { return 45; }
int foo() { return 45; } // Error: multiple definition

关于C++ 结构问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21640824/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com