美文网首页C++
《C++ Primer》6.7 函数指针

《C++ Primer》6.7 函数指针

作者: codinRay | 来源:发表于2017-03-29 20:12 被阅读0次

函数指针

  • 函数的类型由它的返回类型形参类型共同决定。
  • 这样去声明一个指向某函数的指针:
bool fuck(string &, string &);
bool (*pf)(string &, string &) = fuck; // pf旁边的括号是必需的
  • 使用函数指针,我们可以这样取用:
pf = lengthCompare;
pf = &lengthCompare; // 取地址符是可选的
  • 我们还能直接使用指向函数的指针调用该函数,无需提前解引用指针:
bool b1 = pf("fuck", "holy shit");
bool b2 = (*pf)("fuck", "holy shit");
  • 使用后置函数返回类型来使用函数返回一个指向某函数的指针:
string add(string &s) {...};
string cut(string &s) {...};
auto fuc(string::size_type len) -> string(*)(string &s) {...};

int main() {
  string s = "当然是选择原谅她啊。";
  auto pf = fuc(s.length());
  pf(s);
  cout << s << endl;
  return 0;
}

相关文章

网友评论

    本文标题:《C++ Primer》6.7 函数指针

    本文链接:https://www.haomeiwen.com/subject/dpyyottx.html