[英]Initializing array of structures with function pointer member in C++
我在初始化帶有函數指針作為其成員的結構數組時遇到麻煩。
class Record
{
private:
typedef void (*display_fn_t) ();
struct record {
int a;
display_fn_t disp;
};
static const record rec[];
void disp1() { cout << "Display 1 with a string to display" << endl; }
void disp2() { cout << "Display 2 with an integer to display" << endl; }
public:
int find() { /* logic to find the record comes here */ }
void display() {
for (int i = 0; i < 2; i++) {
rec[i].disp();
}
}
}
const Record::record Record::rec[] = {
{ 10, disp1 },
{ 11, disp2 }
};
int main()
{
Record r;
if (r.find())
r.display();
return 0;
}
編譯上面的代碼時,出現以下編譯錯誤:
mca_record.cpp:56:錯誤:類型為'void(Record ::)()'的參數與'void(*)()'不匹配
要使呼叫正常工作,您必須像這樣調用它:
for (int i = 0; i < 2; i++) {
(*rec[i].disp)();
}
並以這種方式初始化表:
const Record::record Record::rec[] = {
{ 10, &Record::disp1 },
{ 11, &Record::disp2 }
};
您的語法錯誤,並且未使用適當的運算符。
修復多種語法錯誤,並剝離不相關的find
操作,然后使用適當的成員函數指針和operator ->*
得到以下內容(執行此操作的幾種方法之一):
#include <iostream>
class Record
{
private:
typedef void (Record::*display_memfn_t)();
struct record
{
int a;
display_memfn_t disp;
};
static const record rec[];
void disp1() { std::cout << "Display 1 with a string to display" << std::endl; }
void disp2() { std::cout << "Display 2 with an integer to display" << std::endl; }
public:
void display();
};
const Record::record Record::rec[] =
{
{ 10, &Record::disp1 },
{ 11, &Record::disp2 }
};
void Record::display()
{
for (size_t i=0; i<sizeof rec/sizeof*rec; ++i)
(this->*(rec[i].disp))();
}
int main()
{
Record r;
r.display();
return 0;
}
輸出量
Display 1 with a string to display
Display 2 with an integer to display
將其與現有代碼進行比較,不要特別指出,指向成員函數的指針不僅僅是指向函數的指針。 它們需要不同的處理方式,並且通常使用不同的操作員。 有關成員訪問的不同方法(變量和函數), 請參見此處 。
祝你好運。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.