我是竹通過函數指針。通過函數指針作爲參數的另一個函數的參數
下面是一個例子代碼:
#include <iostream>
class test
{
inline
void output_plumber_1(int* const arg_out, const int* const arg_in)
{
*arg_out = -*arg_in;
}
inline
void input_plumber_1(int* const arg_out, const int* const arg_in)
{
*arg_out = 2 * (*arg_in);
}
inline
void member_func(void (test::*output_plumber)(int* const arg_out, const int* const arg_in),
void (test::*input_plumber)(int* const arg_out, const int* const arg_in),
int arg)
{
int arg_copy;
(*input_plumber)(&arg_copy, &arg);
arg_copy = arg_copy + 1;
int arg_out;
(*output_plumber)(&arg_out, &arg_copy);
std::cout << arg_out << std::endl;
}
public:
void execute(int arg)
{
void (test::*output_plumber)(int* const arg_out, const int* const arg_in) = &test::output_plumber_1;
void (test::*input_plumber)(int* const arg_out, const int* const arg_in) = &test::input_plumber_1;
member_func(output_plumber, input_plumber, arg);
}
};
int main()
{
test mytest;
mytest.execute(1);
return 0;
}
什麼是應該做?
這是一個相當精益的例子,但本質上我有一個帶有一個成員函數的類的程序,它對一些輸入數據進行操作。在執行操作之前以及在執行操作之後,必須將數據輸入到一組輸入和輸出「管道工」功能中,這些功能修改數據以準備「操作」發生,並且「做一些事情來糾正在「手術發生後」進行初步準備「。
這樣的事情出現在我的程序中,因爲我正在處理只對x> y有效的數據對(x,y)進行操作的算法。 (奇怪的?但是,這是怎麼回事。)
什麼問題?
推測衆多,但是立即編譯器輸出如下:
main.cpp: In member function ‘void test::member_func(void (test::*)(int*, const int*), void (test::*)(int*, const int*), int)’:
main.cpp:27:11: error: invalid use of unary ‘*’ on pointer to member
(*input_plumber)(&arg_copy, &arg);
^
main.cpp:32:11: error: invalid use of unary ‘*’ on pointer to member
(*output_plumber)(&arg_out, &arg_copy);
問題:「這是怎麼回事de做「或」爲什麼不編碼「? –
@JamesRoot爲什麼不編譯 - 我自己編寫代碼,我知道我想要它做什麼,它只是在語法上不正確 – user3728501
如果管道工函數實際上不使用'this',那最好是讓他們成爲非會員。考慮讓'member_func'接受更通用的'std :: function''。 –