【问题标题】:Simple modification of Hello WorldHello World的简单修改
【发布时间】:2016-08-11 20:26:13
【问题描述】:

我是一名初学者 C++ 程序员。某处肯定有简单的错误,但我无法弄清楚为什么它无法编译。

Main.cpp:

#include <iostream>
#include <string>
#include "GUI.h"
#include "GUI.cpp"

int main()
{
    Display("Hello World!");
    return 0;
}

GUI.h

#pragma once
void Display(std::string param0);

GUI.cpp

#include "GUI.h"
void Display(std::string param0)
{
    std::cout << param0;
}

错误是:

Namespace "std" has no member "string" and "cout"

'String' is not a member of 'std'

'String' undeclared identifier

syntax error: missing ')' before identifier 'param0'

'{': missing function header (old-style formal list?)

但是,当我将代码直接粘贴到 Main.cpp 创建时

#include <iostream>
#include <string>

void Display(std::string param0);

void Display(std::string param0)
{
    std::cout << param0;
}

int main()
{
    Display("Hello World!");
    return 0;
}

它工作正常,所以问题可能在于错误使用#includes。

我一直认为 include 指令只是将代码“注入”到 main.cpp 中,它只是为了组织目的和将代码分成更小的部分,但现在我很困惑。

这段代码应该是什么样子?为什么?

这段代码是不是已经有什么不好的编程习惯了?

编辑:感谢您的帮助,它终于编译了,所以我认为应该这样做:

Main.cpp

#include <iostream>
#include <string>
#include "GUI.h"
int main()
{
    Display("Hello World!");
    return 0;
}

GUI.h

#pragma once
#include <iostream>
#include <string>
void Display(std::string param0);

也可以这样做

#ifndef GUI_H
#define GUI_H
#include <iostream>
#include <string>
void Display(std::string param0);
#endif

GUI.cpp

#include "GUI.h"
void Display(std::string param0)
{
    std::cout << param0;
}

【问题讨论】:

  • 您的 GUI.h 中缺少 #include
  • 不包含源 (.cpp) 文件。
  • 另外,请仔细阅读您的学习资料,包括 .cpp 之类的废话。
  • 顺便说一句,#pragma once 不是 标准 语言的一部分。您可能想要使用传统的包含守卫。

标签: c++ windows console


【解决方案1】:

您忘记将#include &lt;string&gt; 添加到GUI.h。无需包含GUI.cpp 文件。

【讨论】:

    猜你喜欢
    • 2019-01-14
    • 1970-01-01
    • 2021-05-19
    • 2016-03-02
    • 2019-03-14
    • 2013-10-14
    • 2019-04-09
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多