关于函数范围的基本C ++问题

时间:2009-01-28 04:17:09

标签: c++ function scope

我刚开始学习C ++,所以你不得不忍受我的无知。有没有办法声明函数,以便可以在不使用它们的函数之前编写它们。我正在使用一个cpp文件(不是我的决定)而且我的函数调用自己,因此没有真正的顺序将它们放入。在使用它们之前#define函数的任何方式或者那种效果? 或者也许是一种用范围运算符标记它们的方法,这种运算符并不意味着它们实际上属于类的一部分?

提前致谢

5 个答案:

答案 0 :(得分:9)

您可以在实施之前编写原型功能。函数原型命名函数,返回类型及其参数的类型。唯一需要在函数调用之上的是原型。这是一个例子:

// prototype
int your_function(int an_argument);

// ...
// here you can write functions that call your_function()
// ...

// implementation of your_function()
int your_function(int an_argument) {
    return an_argument + 1;
}

答案 1 :(得分:4)

我认为您所指的是函数原型

您可以在头文件中定义函数的原型,但在源(.cpp)文件中定义实现

需要引用该函数的源代码只包含头文件,它为编译器提供了足够的信息,以便将函数调用与参数相关联,并返回您正在调用的函数的返回值。

只有在链接阶段才能对源文件解析函数“symbol” - 如果此时不存在函数 implementation ,则会得到一个未解析的符号。

以下是一个例子:

库头文件 - library.h

// This defines a prototype (or signature) of the function
void libFunction(int a);

库源(.cpp)文件 - library.cpp

// This defines the implementation (or internals) of the function
void libFunction(int a)
{
   // Function does something here...
}

客户端代码

#include "library.h"
void applicationFunction()
{
   // This function call gets resolved against the symbol at the linking stage
   libFunction();
}

答案 2 :(得分:4)

您需要的是一个函数声明(又名 prototype )。声明是函数的返回类型,名称和参数列表,没有正文。这些通常在头文件中,但它们不一定是。这是一个例子:

#include< stdio >
using namespace std;

void bar( int x );  // declaration
void foo( int x );  // declaration

int main() {
    foo( 42 );      // use after declaration and before definition
    return 0;
}

void foo( int x ) { // definition
    bar( x );       // use after declaration and before definition
}

void bar( int x ) { // definition
    cout << x;
}

答案 3 :(得分:2)

是。将函数的签名放在文件的顶部,或放在标题(.h)文件中。

所以:

void OtherFunc(int a);

void SomeFunc()
{
    OtherFunc(123);
}

void OtherFunc(int a)
{
    ...
}

答案 4 :(得分:2)

类成员函数在标头中声明,该标头定义了类的接口。此头文件应包含在包含实现的CPP文件的顶部或附近。因此,在CPP文件中定义成员函数的顺序无关紧要,因为所有声明都已包含在内。

从你的问题来看,我会想你正在考虑编写免费功能。您可以使用相同的技术来声明自由函数;但是,我提醒过多的免费功能。

相关问题