关于课程中的方法 [英] About the method in the class
问题描述
虚拟方法的地址存储在类的vir_table中,当我们调用虚拟方法时,我们可以在类中搜索vir_table以获得所需的方法,但是普通方法未存储在vir_table中.因此,当我们通过对象或指针调用普通方法时,如何知道普通方法的地址?
The address of virtual method is stored in the vir_table in class.When we call a virtual method, we can search the vir_table in class to get that the method which we wanted.But the normal method is not stored in the vir_table.So, when we call a normal method by an object or a pointer.How do it know the normal method address?
推荐答案
非虚拟方法就像在这方面,常规的全局函数除外,只是它接受额外隐藏的此指针作为其第一个参数.非虚拟方法的地址是过程地址空间中的固定位置.
这可能是一个愚蠢的示例,但是以下代码:
A non-virtual method is just like a normal global function in this regard except that it accepts an extra hidden this pointer as its first parameter. The address of a non-virtual method is a fix location in your process address space.
This may be a stupid example but the following code:
struct S
{
int i;
void f()
{
printf("%d\n", i);
}
}
S s;
s.f();
...基本上被编译成如下形式:
...is basically compiled to something like this:
struct S
{
int i;
}
void f(S* _this_)
{
printf("%d\n", _this_->i);
}
S s;
f(&s);
知道这一点后,您发出s.f()
方法调用就不会发生魔术.通过将S
实例指定为其第一个隐藏参数(在本例中为&s
),您只需调用S
命名空间中的f()
函数"即可.
唯一的不同是,第一块代码的可读性趋于提高(我认为,尤其是当代码库的大小增加时),并且可以通过将方法f()
设为私有和
Knowing this reveals that there is no magic happening when you issue an s.f()
method call. You just call the f()
"function" residing in the S
namespace by specifying an S
instance as its first hidden parameter (that is &s
in our case).
The only difference is that the readability of the code in the first block tends to be better (in my opinion - especially when the size of codebase increases) and there you can hide method f()
from outer world by making it private and f()
can see the private members of S (this is some kind of documentation and prevention of abuse - converting human coder mistakes into compile errors), the same isn''t true for the second code block that is much like C code. I usually start to explain the beauty of C++ for C coders through a similar example on non-virtual methods. :-)
在程序编译期间会分配常规方法地址
the normal method address gets assigned during the program compilation
float (SomeClass::*my_memfunc_ptr)(int, char *);
// For const member functions, it's declared like this:
float (SomeClass::*my_const_memfunc_ptr)(int, char *) const;
my_memfunc_ptr = &SomeClass::some_member_func;
// This is the syntax for operators:
my_memfunc_ptr = &SomeClass::operator !;
成员函数指针和最快的C ++代理 [ ^ ]
Member Function Pointers and the Fastest Possible C++ Delegates[^]
这篇关于关于课程中的方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!