【问题标题】:Using c++ and trying to "nest" some code使用 c++ 并尝试“嵌套”一些代码
【发布时间】:2016-09-08 21:42:49
【问题描述】:

我目前正在尝试用 C++ 创建一个基本的问答游戏。

以下代码在我尝试运行时会引发错误,如果我不在主类中使用 answer("answer") 而是将其替换为实际代码,则它可以工作。

我想“嵌套”(我不知道技术术语)一些代码,这样我就不必每次都写出来,正如你所看到的,我希望写下任何问题答案(“答案”)。

#include "stdafx.h"
#include <iostream>
#include <string>
using namespace std;

int main()
{
    cout << "QUIZ C++ EDITION!\n";
    cout << "Question 1:\n";
    cout << "What is the colour you get when you mix red and yellow?\n\n";

    question("Orange");

    system("PAUSE");
}

void question(string answer) {
    string input;

    getline(cin, input);

    if (input == answer) {
        cout << "\nCorrectimundo!\n";
    }
    else
    {
        cout << "\nWrongimundo.\n";
    }
    return;
}

我感觉这是语法错误的情况,但不幸的是 IDE 没有显示错误的位置,它仅在我运行程序时发生。

【问题讨论】:

  • 运行时遇到什么错误?

标签: c++ input namespaces std iostream


【解决方案1】:

看起来您正在尝试创建一个函数。我可以帮忙吗?

– Clippy (1997-2007 RIP)

有两种方法可以做到这一点。一种是在第一次使用之前转发声明question

void question(string answer);

int main()
{
    ...
    question("Orange")
    ...
}

void question(string answer)
{ ... }

前向声明是对编译器的承诺,question 将在其他地方完全定义,可能在此文件的稍后部分,可能在另一个文件中,可能在库中。但它必须在某个地方定义,否则程序会编译,但不会链接。

另一个是在第一次使用之前完全定义question

void question(string answer)
{ ... }

int main()
{
    ...
    question("Orange")
    ...
}

我更喜欢第二种方法,因为不可能陷入这样的陷阱:

void question(int answer);

int main()
{ 
    ...
    question(42)
    ...
}

void question(string answer)
{ ... }

由于更改 question 的前向声明并忘记更改定义而导致链接器错误。

【讨论】:

  • 不过,这是一个向前的声明,绝对不是“定义”[ition]
  • 我总是把定义/声明的术语放在后面。我只是查了一下,以确保我仍然把它倒退了。糟糕的互联网。坏的。坏的。修复。
  • 我们信任 Clippy
  • 天哪。 @Cheersandhth.-Alf 是你发现或做到的?
【解决方案2】:

您需要提供函数question 的声明,然后才能在main 中使用它。添加

void question(string answer);

main的定义之前。

【讨论】:

    【解决方案3】:

    在C++中,你必须先声明一个函数,然后才能使用它(注意,定义也是一个声明),但在行前没有提到函数question

    question("Orange");
    

    当它实际上试图被调用时。添加声明:

    void question(string answer);
    
    int main()
    {
        // the rest of code ...
    

    【讨论】:

      【解决方案4】:

      你忘了声明你的函数,你可以在 main 之前声明它,或者在 main 之前写整个函数。

      【讨论】:

        【解决方案5】:

        你需要在你的main之前添加:

        空问题(字符串值);

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2022-01-13
          • 1970-01-01
          • 2023-04-04
          • 2021-12-22
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2011-07-26
          相关资源
          最近更新 更多