简体   繁体   English

这种C ++技术用于向类调用添加类型是什么?

[英]What is this C++ technique for adding types to a class called?

I've just found some C++ code (at http://msdn.microsoft.com/en-us/library/k8336763(VS.71).aspx ), which uses a technique I've never seen before to add types to an existing class: 我刚刚发现了一些C ++代码(在http://msdn.microsoft.com/en-us/library/k8336763(VS.71).aspx ),它使用了我以前从未见过的技术来添加类型现有的课程:

class Testpm {
public:
   void m_func1() { cout << "m_func1\n"; }
   int m_num;
};

// Define derived types pmfn and pmd.
// These types are pointers to members m_func1() and m_num, respectively.
void (Testpm::*pmfn)() = &Testpm::m_func1;
int Testpm::*pmd = &Testpm::m_num;

int main() {
   Testpm ATestpm;
   Testpm *pTestpm = new Testpm;

   // Access the member function
   (ATestpm.*pmfn)();
   (pTestpm->*pmfn)();   // Parentheses required since * binds

   // Access the member data
   ATestpm.*pmd = 1;
   pTestpm->*pmd = 2;

   cout  << ATestpm.*pmd << endl
         << pTestpm->*pmd << endl;
}

Can someone please tell me what this technique for defining derived types is called, or point me to some documentation on it? 有人可以告诉我这种用于定义派生类型的技术是什么被调用,或者指向我的一些文档? I've never come across it in 13 years of using C++, and would like to end my ignorance. 我在使用C ++的13年中从未遇到过这种情况,并希望结束我的无知。

The comment is incorrect: pmfn and pmd are not "derived types" at all (they are not even types!). 注释不正确:pmfn和pmd根本不是“派生类型”(它们甚至不是类型!)。 They are pointers to members . 他们是成员的指针

I don't think they're "adding types" to the class. 我不认为他们在课堂上“添加类型”。 They seem to be just defining types of pointers to member functions and member data of the class, and then using those to access the member function and data member. 它们似乎只是定义了指向成员函数和类成员数据的指针类型,然后使用它们来访问成员函数和数据成员。 Similar to how you'd declare types to non-member functions, but being members of the class the syntax differs. 与向非成员函数声明类型的方式类似,但作为类的成员,语法不同。

From this site here 从这个网站在这里

Regarding their syntax, there are two different types of function pointers: On the one hand there are pointers to ordinary C functions or to static C++ member functions. 关于它们的语法,有两种不同类型的函数指针:一方面有指向普通C函数或静态C ++成员函数的指针。 On the other hand there are pointers to non-static C++ member functions. 另一方面,有指向非静态C ++成员函数的指针。 The basic difference is that all pointers to non-static member functions need a hidden argument: The this-pointer to an instance of the class. 基本区别在于所有指向非静态成员函数的指针都需要一个隐藏参数:this-pointer指向类的实例。 Always keep in mind: These two types of function pointers are incompatible with each other. 始终牢记:这两种类型的函数指针彼此不兼容。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM