在 C++ 中,您通常在哪里声明和定义 class 之外的函数?

Where do you typically declare and define functions outside a class in c++?

我学习 C++ 已经有一段时间了,想开始实际的 application/software 开发。问题是我很难弄清楚如何准确设置项目的一些更实际的方面。我今天的问题是,如果我有一个未在标准 class 结构中声明和定义的函数,我到底应该在哪里声明和定义它,或者最常见的是在哪里声明和定义它?您观看的大多数教程都会在 main() 之上的 main.cpp 中声明一个函数,然后在 main() 之下定义它,但我认为这只是出于教学目的,而不是实际应用。您是否应该像使用 classes 一样创建函数头文件和源文件?

免费功能

对于自由函数,以下方案是最常见的:

  1. 将函数的定义放在 .cpp 文件中。
  2. 在 header 中声明函数。

[Note: In C++ there's no need for the extern before a function declaration because by default all functions have external linkage. However, I use it to emphasize that this is a declaration of an externally defined function.]

例如,如果您有一个名为 int foo() 的免费函数 在 .cpp 文件中放置它的定义:

int foo() {
  // does what ever...
}

然后在 header 文件(例如 .hpp.h)中放置声明:

int foo();

成员函数

对于成员函数,典型的方案是:

  1. class 定义放入 header 文件中(例如,.hpp.h)。
  2. 将成员函数定义放在 .cpp 文件中。

[Note: Mind however, that there's the following difference between defining a member function in its class body and definining it elsewhere. In the first case the member function is declared inline.]

例如,如果你有一个 class Bar 有一个成员函数 int baz():

您可以将 class 定义放入 header 文件中:

class Bar {
  public:
  int baz();
};

以及成员函数在各自.cpp文件中的定义:

int Bar::baz() {
  // do what ever...
}

[Note: These rules are not typical and putting a function definition above or below main is perfectly fine.]

您需要在 .h 文件中声明(原型)函数,然后在 .cpp 文件中实现它。示例:

main.cpp:

#include "header.h"
int main()
{
    // use the functions
    printf("%f, %f", add(10, 10), sub(64, 2.8));
}

header.h:

double add(double, double);       // function declarations
double sub(double, double);

header.cpp:

#include "header.h"
double add(double a, double b)    // function implementations
{
    return a + b;
}
double sub(double a, double b)
{
    return a - b;
}

是的,您可以将主 cpp 文件与单独的 header/source 文件一起用于您自己的函数。像这样:

/main.cpp

#include "myFunctions.h"

int main(){

    printSum(5, 5);
    return 0;    
}

/myFunctions.h

#ifndef MYFUNCTIONS_H
#define MYFUNCTIONS_H

void printSum(int, int);

#endif

/myFunctions.cpp

#include "myFunctions.h"

void printSum(int num1, int num2){

    cout << num1 + num2 << "\n"

}