编写在另一个 .cpp 文件中调用的函数

writing functions that are called in another .cpp file

我想确保我正确地调用了函数。另一个 .cpp 中的函数是 makeDeck()shuffle()。我也不知道如何制作相关的头文件或它们何时有用。有人可以编写或引导我完成我的 deck.cppdeck.h 文件的语法,这些文件将与以下内容一起使用: main.cpp

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


int main() {
  int size;
  do {
    cout << "Enter size of deck (5-50): " << endl;
    cin >> size;
  } while (size<5 || size>50);

  int** deck[size] = makeDeck(size);
  shuffle(deck);

  int score = 0;
  char guess = NULL;

  for (int** i = **deck; *i != NULL; i++) {
    cout << "Score: " + score << endl;
    cout << "Current card: " + *i<< endl;
    cout << "Will the next card be higher (high) or lower (low) than " + *i + "?" << endl;
    cin << guess;
    if (guess == "higher" || guess == "high") {
      if (*(i + 1) > *i)
        score++;
      else
        score--;
    }
    if (guess == "lower" || guess == "low") {
      if (*(i + 1) < *i)
        score++;
      else
        score--;
    }
  }
}

通常,当您有 类 时,会使用 .h 文件,但如果您认为您可能会在另一个项目中使用它们,或者您想要一个更清晰的主文件,您也可以将它们用于函数。您有正确的文件 #included,但对于实际的 .h 和 .cpp 文件,您需要如下内容:

deck.h
#ifndef DECK_H
#define DECK_H

    int** makedeck(const int&);
    void shuffle(int**);

#endif    //DECK_H

deck.cpp
#include "deck.h"
    int** makedeck(const int& size)
    {
        //Do something
    }

    void shuffle(int** deck)
    {
        //Do something else
    }

对于 main() 中不需要的任何函数,您可以在 .h 文件中进行声明,然后在 .cpp 中进行定义。两者之间没有真正的区别 在 main 中单独声明函数并在语法方面将它们分成多个文件,只需确保将 .h 文件包含在任何需要使用您在 .h 中声明的函数的文件中。