我可以在 c++ 中使用整数指针调用类的成员函数吗?

Can i call a member function of a class using integer pointer in c++

本文关键字:成员 函数 调用 指针 c++ 整数 我可以      更新时间:2023-10-16
class ABC // class ABC
{
public:
    void f()
    {
        cout <<"hi";
    }
};
int main() //main method
{
    ABC d;//object of class ABC
    int *p=reinterpret_cast<int*>(&d);
     p->f();// trying to call function f by taking address of object
    return 0;
}

您从字面上获取原始数据,而不考虑语言的对称性。

编译器将允许,(尽管逻辑上它可能不正确)

int *p=reinterpret_cast<int*>(&d); 

但它不会为 int 找到任何f()

所以p->f();肯定会给出编译器错误。