簡體   English   中英

在局部變量 c++ 的 scope 中調用全局 function 時,全局變量優先於局部變量

[英]Global variable priority over local variable when global function called in scope of local variable c++

我只是想澄清一下我的知識差距。

給定以下代碼:

我本來預計會打印“Hi”,這純粹是因為在 foo 的 scope 中,FuncA 的定義被覆蓋,因此應該被調用。 這不會發生,如此處所示https://onlinegdb.com/LzPbpFN3R

有人可以解釋一下這里發生了什么嗎?

std::function<void()> FuncA;

void FuncB() {
    if (FuncA) {
        FuncA();
    }
}

struct Foo {
    void FuncA() {
        std::cout << "Hi";
    }
    
    void FuncC() {
        FuncB();
    }
};

int main()
{
    Foo foo{};
    
    foo.FuncC();
    
    return 0;
}

只要您撥打免費的 function,您就不再在 class 內。 而且你已經失去了特殊的this指針。 一種(相當 C-ish)的方式可能是:

void FuncB(struct Foo* a) {   // expect a pointer to a Foo object
    a->FuncA();               // call the method on the passed object
}

struct Foo {
    void FuncA() {
        std::cout << "Hi";
    }
    
    void FuncC() {
        FuncB(this);         // pass the special this pointer to the function
    }
};

暫無
暫無

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

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