我只是想澄清我的知識差距。
鑒于以下代碼:
我本來希望列印“Hi”,這純粹是基于在 foo 的范圍內,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;
}
uj5u.com熱心網友回復:
一旦你呼叫了一個自由函式,你就不再是班里的人了。并且您丟失了特殊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
}
};
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/402512.html
標籤:
