据我所知,每个创建的对象都有自己的地址,每个对象的方法也有自己的地址。我想用以下想法来验证这一点:
步骤1:构建具有公共方法的类A,其名称为“method”。
步骤2:在A类中创建两个对象,它们是对象“b”和对象“c”。
步骤3:使用函数指针访问“b.method”和“c.method”的地址,检查它们是否相等。
但我在步骤3中遇到了问题,并找到了各种方法来解决但失败了。所以我在这里发帖请教大家如何验证我上面所说的。感谢大家!这是我的 C++ 代码:
#include<iostream>
using namespace std;
class A
{
public:
int a;
void method()
{
//do something
}
static void (*fptr)();
};
int main()
{
A b, c;
A::fptr= &(b.method); //error: cannot convert 'A::method' from type
// 'void(A::)()' to type 'void (*)()'
cout << A::fptr << endl;
A::fptr= &(c.method); //error: cannot convert 'A::method' from type
//'void(A::)()' to type 'void (*)()'
cout << A::fptr << endl;
return 0;
}
Run Code Online (Sandbox Code Playgroud)
谢谢大家!我想知道这个问题很长一段时间了,现在我自己找到了答案,即使创建了数百个对象,在内存上也只有一个“method()”被创建。所有创建的想要使用此方法的对象都必须找到此方法的地址。这是证明我所说的代码:
#include<iostream>
using namespace std;
class A
{
public:
int a;
void method()
{
//do something
}
static void (*fptr)();
};
int main()
{
A b,c;
if(&(b.method)==&(c.method))
{
cout<<"they are same\n";
}
else
{
cout<<"they are not same\n";
}
return 0;
}
Run Code Online (Sandbox Code Playgroud)