簡體   English   中英

C ++無法調用某些函數

[英]C++ cannot call some functions

我敢肯定有一個簡單的解釋,但是我不能在其他一些函數下面調用這些函數。

int methodOne() {
    std::cout << "Method 1";
    methodTwo(); //Problem is here. I cannot call methodTwo()
    return 0;
}

int methodTwo() {
    std::cout << "Method 2";
    return 0;
}

int main() {
    methodOne();
}
int methodTwo();  // forward declaration

int methodOne() {
    std::cout << "Method 1";
    methodTwo(); // works!
    return 0;
}

int methodTwo() {
    std::cout << "Method 2";
    return 0;
}

C ++編譯器不會回溯。 您必須先聲明一個函數,然后才能使用它。 鏈接器可以在以后找出細節,但是您必須首先讓編譯器知道該函數,這就是前向聲明的作用。

您只需要在MethodOne的聲明之前向前聲明MethodTwo

首先,有關術語的一點:在C ++中,術語“ 方法”從不應用於獨立功能,而僅應用於成員函數。

正如您在下面看到的那樣,您的示例僅對獨立功能有意義,因此使用術語“方法”是很容易引起誤解的。

在C ++中,必須在使用前聲明一些內容。

對於免費函數,這意味着您不能在聲明文本之前的某個點調用函數:

void foo() { bar(); }   // NO GOOD!
void bar() {}

但是,當您編寫類似的類聲明時

struct S
{
    void foo() { bar(); }
    void bar() {}
};

編譯器(基本上)將其轉換為

struct S
{
    inline void foo();
    inline void bar();
};

inline void S::foo() { bar(); }
inline void S::bar() {}

正如您所看到的,在聲明它之前,不會調用此經過轉換的更基本的代碼bar

簡而言之,編譯器需要在使用前了解一些內容。

最后,對於獨立功能,解決問題的一種方法是對聲明進行重新排序 ,另一種方法是先聲明 bar函數,即前向聲明

重新排序通常會節省您的工作,因為具有前向聲明意味着必須同時保留前向聲明和定義。 新手經常會遇到前向聲明與預期定義不同的情況,因此他們會遇到神秘的編譯錯誤。 通常最好避免這種情況,只需對定義重新排序即可: bar首先,因為它由foo調用。

像這樣添加前向聲明:

int methodTwo(); //Forward declaration

int methodOne() {
    std::cout << "Method 1";
    methodTwo(); //Problem is here. I cannot call methodTwo()
    return 0;
}

int methodTwo() {
    std::cout << "Method 2";
    return 0;
}

int main() {
    methodOne();
}

如果未在要調用的函數之前聲明任何函數,則需要向前聲明它們。

int FunctionTwo();

順便說一句,方法通常表示類中的函數。

暫無
暫無

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

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