我试图通过它们的指针调用函数。编译这段代码时,我收到错误说 void 类型的表达式不能转换为其他类型,但我在调用函数之前检查函数是否返回 void。还有另一种方法可以做到这一点吗?
class FuncBase {
public:
FuncBase(string n, string ret, string arg1, string arg2): name(n), retval(ret), a1(arg1), a2(arg2) {}
string getName() const { return name; }
string getRet() const { return retval; }
string getA1() const { return a1; }
string getA2() const { return a2; }
virtual void call() = 0;
private:
string name, retval, a1, a2;
};
template <typename ret, typename arg1, typename arg2>
class Func: public FuncBase {
public:
Func(string n, string r, string ar1, string ar2, ret(*fc)(arg1, arg2)):
FuncBase(n, r, ar1, ar2), func(fc) {}
void call() {
arg1 ar1;
arg2 ar2;
cout << "You chose the " << getName() << " function" << endl;
cout << "Enter a " << getA1() << ": ";
cin >> ar1;
cout << "Enter a " << getA2() << ": ";
cin >> ar2;
if (getRet() != "void") {
ret val = (*func)(ar1, ar2);
cout << getName() << " returned " << val << endl;
}
else (*func)(ar1, ar2);
cout << endl;
}
private:
// pointer to function
ret(*func)(arg1, arg2);
};