c++ - 声明一个没有内容的函数; - 然后是内容 {} - C++

标签 c++ function overloading declaration

我不确定术语,所以我不知道如何表达我的标题;如果有人想用正确的术语对其进行编辑,那很好。

当我编写代码时,我总是按时间顺序进行。我把我的主线放在底部,然后向上移动。但是,我最近阅读了一个教程,其中做了一些我以前从未见过的事情。

在顶部,包含之后,程序员写道:

void inccell(int pos, int width, unsigned char *board);
void deccell(int pos, int width, unsigned char *board);

我以前没见过这个;我总是做 void myfunction (args) { stuff }。我还没有在 ; 的上下文中看到它。在此之后,在程序的更下方,他定义了函数的内容:

void inccell(int pos, int width, unsigned char *board)
{
    ++board[(pos-width)-1];
    ++board[ pos-width   ];
    ++board[ pos-width +1];
    ++board[ pos-1       ];
    ++board[ pos+1       ];
    ++board[(pos+width)-1];
    ++board[ pos+width   ];
    ++board[ pos+width+1 ];

    return;
}

void deccell(int pos, int width, unsigned char *board)
{
    --board[(pos-width)-1];
    --board[ pos-width   ];
    --board[ pos-width +1];
    --board[ pos-1       ];
    --board[ pos+1       ];
    --board[(pos+width)-1];
    --board[ pos+width   ];
    --board[ pos+width+1 ];

    return;
}

带有 ;{ } 的函数的参数是相同的,据我所知这不是“重载”;我相信使用了重载,因此可以调用具有不同参数集的函数,即 myfunc(myint, mystr, mybool)myfunc(myint, mystr) 都可以有效。

我的说法可能是错误的。

但是,有人可以向我解释一下为什么他在顶部声明函数,如果他没有重载,这样做的目的是什么?

谢谢。

最佳答案

那些是函数声明。它们只是通知编译器这些函数的存在和签名,以便它们的定义可以出现在调用点之后:

void foo(); // DECLARATION

int main()
{
    foo(); // CALL (would be illegal without the declaration, because the compiler
           //       wouldn't know about foo(), since it hasn't met its definition yet)
}

#include <iostream>

void foo() // DEFINITION
{ 
    std::cout << "Hello, world!"; 
}

关于c++ - 声明一个没有内容的函数; - 然后是内容 {} - C++,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16750876/

相关文章:

c++ - 浮点异常(核心转储

function - 如何从函数返回值 - React Native

matlab - 在 Octave 中重载内置函数时内置函数的行为不一致

locale - 如何在不收到警告且不使用类型类的情况下重载符号?

java - 在方法重载中传递不同数据类型的值

c++ - 如何检查派生类的类型? (C++ Instanceof)

c++ - FFMPEG 在 C++ 中对 'avcodoec_open2' 的 undefined reference

javascript - 如何在 jquery 完成之前停止函数?

c++ - "nicer"替代局部变量名称前缀?

swift - UITextField + 计时器问题 - 检查 "Editing Changed"但只有一次启动计时器?