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

writing functions that are called in another .cpp file

本文关键字:函数 调用 另一个 cpp 文件      更新时间:2023-10-16

我想确保我正确调用功能。另一个.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文件,但是如果您认为您可以在另一个项目中使用它们,或者您想拥有一个清洁器的MAIM,则可以将它们用于功能文件。您拥有正确的文件#include D,但是对于实际的.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中声明的函数的文件中。