【问题标题】:what is the meaning of this std::string constructor这个 std::string 构造函数的含义是什么
【发布时间】:2016-12-15 01:39:17
【问题描述】:

今天我试图研究一段代码,但我被这行卡住了。

std::vector<std::string(SomeClassInterface::*)()> ListOfFnPointers;

这个 std::string 构造函数是什么意思?我经历了this,但我不知道这意味着什么。

在代码中用作,

if (!ListOfFnPointers.empty())
{
    std::vector<std::string> StringList;
    for (auto Fn : ListOfFnPointers)
    {
        StringList.push_back((pSomeClassObj->*Fn)());
    }
    ...
}
  1. 那个声明是什么意思?
  2. 这个函数到底用pSomeClassObj-&gt;*Fn做什么?

【问题讨论】:

  • 提示:ListOfFnPointers 这个名字很重要。
  • 谢谢伙计。我从没想过函数指针。

标签: c++ string c++11 stdstring


【解决方案1】:

std::string构造函数无关。

std::string(SomeClassInterface::*)()pointer to member function的类型,成员函数属于SomeClassInterface类,返回std::string,不带参数。

-&gt;*pointer-to-member access operator(也是 .*)。 (pSomeClassObj-&gt;*Fn)() 会调用pSomeClassObj 上的成员函数,它应该是一个SomeClassInterface* 类型的指针。

【讨论】:

    【解决方案2】:

    它不是构造函数,它是一个指向函数的指针,没有返回 std::string 的参数。

    for (auto Fn : ListOfFnPointers)
    {
        StringList.push_back((pSomeClassObj->*Fn)());
    }
    

    上面的推回是有效的,因为 (pSomeClassObj->*Fn)() 是对这些函数的调用,结果是 std::string。

    更新:

    1. 它是函数指针的 std::vector 的声明。每个函数都属于 SomeClassInterface,不带参数并返回 std::string。

    2. 如果此代码 (pSomeClassObj->*Fn)() 调用对象 pSomeClassObj 的函数,其中 Fn 是指向此函数和 pSomeClassObj 成员的指针。

    【讨论】:

      【解决方案3】:

      如果你使用C++11,你可以这样写代码:

      using FunctionPointer = std::string (SomeClassInterface::*) ();
      std::vector<FunctionPointer> ListOfFnPointers;
      

      您可以阅读此链接:http://en.cppreference.com/w/cpp/language/type_alias

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2017-09-09
        • 1970-01-01
        • 2016-11-01
        • 2015-12-20
        • 2023-03-16
        相关资源
        最近更新 更多