【问题标题】:non-static member function reinterpret_cast failed非静态成员函数 reinterpret_cast 失败
【发布时间】:2016-10-18 04:47:47
【问题描述】:

代码:

#include <iostream>

using namespace std;

struct item
{
   int f1() {}
   double f2() {}

   static int  g1() {}
   static double  g2() {}

   void f0();
};
void item::f0()
{
   auto c1 = reinterpret_cast<decltype(f2)>(f1);
   auto c2 = reinterpret_cast<decltype(g2)>(g1);

   auto c3 = reinterpret_cast<decltype(&f2)>(f1);
   auto c4 = reinterpret_cast<decltype(&g2)>(g1);
}
int main()
{
   cout << "Hello world!" << endl;
   return 0;
}

错误信息:

main.cpp|17|error: invalid use of non-static member function|
main.cpp|18|error: invalid cast from type ‘int (*)()’ to type ‘double()’|
main.cpp|20|error: ISO C++ forbids taking the address of an unqualified or parenthesized non-static member function to form a pointer to member function.  Say ‘&item::f2’ [-fpermissive]|
main.cpp|20|error: invalid use of member function (did you forget the ‘()’ ?)

我的问题: 作为参数传递的成员函数将自动转换为指针,所以我尝试将参数转换为指针,但仍然失败。 我不明白为什么非静态成员函数根本不起作用 情况。

【问题讨论】:

    标签: c++ member non-static reinterpret-cast


    【解决方案1】:

    你需要转换f1的返回值,而不是f1。使用:

      auto c1 = reinterpret_cast<decltype(f2())>(f1());
                                                   ^^ Call the function
    

    对其他行进行类似的更改。

    我误解了你想要做什么。以下应该有效:

       auto c1 = reinterpret_cast<decltype(&item::f2)>(&item::f1);
       auto c2 = reinterpret_cast<decltype(&g2)>(g1);
    
       auto c3 = reinterpret_cast<decltype(&item::f2)>(&item::f1);
       auto c4 = reinterpret_cast<decltype(&g1)>(g2);
    

    f1 是一个非staticmember 函数。您可以使用f1() 调用它。但是,如果没有函数调用语法,非静态成员函数不会自动衰减为成员函数指针。要获取struct 的成员函数指针,您需要使用&amp;item::f1

    【讨论】:

    • 我想让 c1 成为一个函数,除了 reinterpret_cast 不能将 int 转换为 double
    • @R Sahu,太棒了!它有效,但你能解释一下为什么吗?
    • @Gr.Five,希望添加的解释有意义。
    猜你喜欢
    • 2020-10-04
    • 1970-01-01
    • 1970-01-01
    • 2014-04-14
    • 2011-01-27
    • 2021-12-03
    • 1970-01-01
    • 1970-01-01
    • 2011-05-31
    相关资源
    最近更新 更多