语法
expression .* expression
expression ->* expression
备注
指向成员的指针运算符(. * 和->* )返回表达式左侧指定的对象的特定类成员的值。 右侧必须指定该类的成员。 下面的示例演示如何使用这些运算符:
// 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 成员。
二元运算符 .* 将其第一操作数(必须是类类型的对象)与其第二操作数(必须是指向成员的指针类型)组合在一起。
二元运算符 > * 将其第一个操作数(必须是指向类类型的对象的指针)与其第二个操作数(必须是指向成员的指针类型)组合在一起。
在包含 .* 运算符的表达式中,第一操作数必须是类类型且可访问,而指向第二操作数中指定的成员的指针或可访问类型的成员的指针明确从该类派生并且可供该类访问。
在包含-> * 运算符的表达式中,第一个操作数必须为第二个操作数中指定的类型的 “指向类类型的指针” 类型,或者必须是从该类明确派生的类型。
示例
考虑以下类和程序段:
// 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.
}
. * 或->* 指向成员的指针运算符的结果是在指向成员的指针的声明中指定的类型的对象或函数。 因此,在前面的示例中,表达式 ADerived.*pmfnFunc1() 的结果是指向返回 void 的函数的指针。 如果第二操作数是左值,则此结果为左值。
该博文为原创文章,未经博主同意不得转载,如同意转载请注明博文出处,本文章博客地址:https://blog.youkuaiyun.com/it_cplusplus/article/details/118835508
本文详细介绍了C++中指向成员的指针运算符.*和->*的语法和用法,包括它们在调用成员函数和访问成员变量时的应用,并通过示例进行说明。
1105

被折叠的 条评论
为什么被折叠?



