簡體   English   中英

有關功能范圍的C ++基本問題

[英]Basic C++ question regarding scope of functions

我剛剛開始學習C ++,所以您必須忍受我的無知。 有沒有一種方法來聲明函數,以便可以在不使用函數的情況下引用它們而無需對其進行引用。 我正在使用一個cpp文件(不是我的決定),並且我的函數調用了自己,因此實際上並沒有適當的順序放置它們。可以在使用它們之前#define函數的某種方法嗎? 還是一種使用范圍運算符標記它們的方法,而這些運算符實際上並不意味着它們實際上是類的一部分?

提前致謝

您可以在實現它們之前編寫函數原型 函數原型為函數命名,其返回類型及其參數的類型。 調用函數之上唯一需要的就是原型。 這是一個例子:

// 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;
}

我認為您指的是一個函數原型

在這里可以在頭文件中定義函數的原型,而在源(.cpp)文件中定義實現。

需要引用該函數的源代碼僅包含頭文件,該頭文件為編譯器提供了足夠的信息,以使函數調用與所調用函數的參數和返回值相關聯。

僅在鏈接階段,函數“ symbol”才針對源文件進行解析-如果此時函數實現尚不存在,則您將獲得未解析的符號。

這是一個例子:

庫頭文件-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();
}

您需要的是一個函數聲明 (即原型 )。 聲明是沒有主體的函數的返回類型,名稱和參數列表。 這些通常位於頭文件中,但不一定必須如此。 這是一個例子:

#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;
}

是。 將函數的簽名放在文件的頂部或頭(.h)文件中。

所以:

void OtherFunc(int a);

void SomeFunc()
{
    OtherFunc(123);
}

void OtherFunc(int a)
{
    ...
}

類成員函數在定義類接口的標頭中聲明。 此頭文件應包含在包含實施的CPP文件的頂部或頂部附近。 因此,在CPP文件中定義成員函數的順序無關緊要,因為已經包含了所有聲明。

根據您的問題,我想您正在考慮編寫自由函數。 您可以使用相同的技術來聲明自由函數。 但是,我告誡不要使用過多的免費功能。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM