我已經搜索了很多,但無法找出正確的語法。我正在嘗試的所有結果都會導致一些語法錯誤。沒有成員函式,我可以編譯它。
這是我的示例:
class TestClass
{
public:
typedef bool (TestClass::* demoFunc)(int);
struct Container
{
Container(demoFunc func)
: func(func)
{}
demoFunc func;
};
Container* containers;
bool foo1(int dummy) { return true; }
bool foo2(int dummy) { return true; }
void InvokeFunction(int i)
{
TestClass::Container container = containers[i];
// How do I call the function here?
bool result = container.func(0); // here is the error
}
};
int main()
{
TestClass testClass;
testClass.containers = new TestClass::Container[]
{
TestClass::Container(&TestClass::foo1),
TestClass::Container(&TestClass::foo2),
};
testClass.InvokeFunction(0);
testClass.InvokeFunction(1);
}
這是編譯器錯誤:
明顯呼叫的括號前的運算式必須具有(指向)函式型別
uj5u.com熱心網友回復:
該運算子->*允許您使用指向實體的指標來呼叫成員函式。該運算子.*允許您直接使用實體或對實體的參考來呼叫成員函式。
您可以使用它們,后跟您的成員函式地址,以便呼叫該函式。
例如
struct Test
{
bool foo(int val){ return true; }
};
int main()
{
Test test_instance;
Test* test_pointer = &test_instance;
Test& test_reference = test_instance;
auto FuncAddress = &Test::foo;
//calling foo using pointer
(test_pointer->*FuncAddress)(0);
//calling foo using directly the instance
(test_instance.*FuncAddress)(0);
//calling foo using a reference to the instance
(test_reference.*FuncAddress)(0);
return 0;
}
uj5u.com熱心網友回復:
取消參考/呼叫成員指標需要一個目標物件(TestClass在本例中為 型別)。
大概你想使用this:bool result = (this->*container.func)(0);
uj5u.com熱心網友回復:
Pointers_to_members語法并不簡單,在您的情況下,它將是:
bool result = (this->*(container.func))(0);
作為替代,std::invoke可以使用 (C 17)
std::invoke(container.func, this, 0);
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/315015.html
下一篇:更改陣列會復制資料嗎?
