指向成员的指针运算符:. *和- >*

expression .* expression
expression –>* expression

备注

指向成员的指针运算符,。* 和 – AMP_GT*,返回特定的类成员的值在表达式的左侧指定对象的。 右侧必须指定类的成员。 下面的示例演示如何使用这些运算符:

// expre_Expressions_with_Pointer_Member_Operators.cpp
// compile with: /EHsc
#include <iostream>

using namespace std;

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
                        // less tightly than the function call.

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

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

Output

m_func1
m_func1
1
2

在前面的示例中,为成员, pmfn的指针,用于调用成员函数 m_func1。 指向成员, pmd的其他指针,用于访问 m_num 成员。

二元运算符。* 合并其第一个操作数,必须是类类型对象,以及其第二个操作数对象,必须是指向成员的指针类型。

二元运算符 – AMP_GT* 合并其第一个操作数,必须是指向类类型对象,以及其第二个操作数对象,必须是指向成员的指针类型。

在表达式包含。* 运算符,第一个操作数必须是,并且可访问,指向成员的指针的类类型指定在第二个操作对象或一个可访问的类型明确地从派生并可以访问该类。

在包含 – AMP_GT* 运算符的表达式,第一个操作数必须是类型 “对类类型的指针在第二个操作对象指定的”的类型,或者必须从该类明确派生的类型。

示例

请考虑类和程序片段:

// expre_Expressions_with_Pointer_Member_Operators2.cpp
// C2440 expected
class BaseClass {
public:
   BaseClass(); // Base class constructor.
   void Func1();
};

// Declare a pointer to member function Func1.
void (BaseClass::*pmfnFunc1)() = &BaseClass::Func1;

class Derived : public BaseClass {
public:
   Derived();  // Derived class constructor.
   void Func2();
};

// Declare a pointer to member function Func2.
void (Derived::*pmfnFunc2)() = &Derived::Func2;

int main() {
   BaseClass ABase;
   Derived ADerived;

   (ABase.*pmfnFunc1)();   // OK: defined for BaseClass.
   (ABase.*pmfnFunc2)();   // Error: cannot use base class to
                           // access pointers to members of
                           // derived classes. 

   (ADerived.*pmfnFunc1)();   // OK: Derived is unambiguously
                              // derived from BaseClass. 
   (ADerived.*pmfnFunc2)();   // OK: defined for Derived.
}

结果。* 或 – AMP_GT* 指向成员的指针运算符位于指针的声明指定类型的对象或函数对成员。 因此,在前面的示例,该表达式 ADerived.*pmfnFunc1() 的结果是指向返回 void 的功能。 ,如果第二个操作数是左值,此结果是左值。

备注

如果结果的一个指向成员的指针运算符是函数,则可以使用该结果,仅当对一个操作数函数调用运算符。

请参见

参考

C++运算符

运算符优先级和结合性