c ++ 函数的esp指针
Create a class along with data member and member functions and then access the member functions by using a pointer in C++.
创建一个类以及数据成员和成员函数,然后使用C ++中的指针访问成员函数。
如何通过指针访问成员函数? (How to access a member function by pointer?)
To access a member function by pointer, we have to declare a pointer to the object and initialize it (by creating the memory at runtime, yes! We can use new keyboard for this).
要通过指针访问成员函数 ,我们必须声明一个指向该对象的指针并将其初始化(通过在运行时创建内存,是的!我们可以为此使用新键盘)。
The second step, use arrow operator -> to access the member function using the pointer to the object.
第二步,使用箭头运算符->使用指向对象的指针访问成员函数。
Syntax:
句法:
//pointer to object declaration
class_name *pointe_name;
//memory initialization at runtime
pointer_name = new class_name;
//accessing member function by using arrow operator
pointer_name->member_function();
Example:
例:
In the below example - there is a class named Number with private data member num and public member functions inputNumber(), displayNumber().
在下面的示例中-有一个名为Number的类,具有私有数据成员num和公共成员函数inputNumber()和displayNumber() 。
In the example, we are creating simple object N and a pointer to the object ptrN and accessing the member functions by using simple object N and the pointer to the object ptrN.
在该示例中,我们将创建简单对象N和指向对象ptrN的指针,并通过使用简单对象N和指向对象ptrN的指针来访问成员函数。
Program:
程序:
#include <iostream>
using namespace std;
class Number
{
private:
int num;
public:
//constructor
Number(){ num=0; };
//member function to get input
void inputNumber (void)
{
cout<<"Enter an integer number: ";
cin>>num;
}
//member function to display number
void displayNumber()
{
cout<<"Num: "<<num<<endl;
}
};
//Main function
int main()
{
//declaring object to the class number
Number N;
//input and display number using norn object
N.inputNumber();
N.displayNumber();
//declaring pointer to the object
Number *ptrN;
ptrN = new Number; //creating & assigning memory
//printing default value
cout<<"Default value... "<<endl;
//calling member function with pointer
ptrN->displayNumber();
//input values and print
ptrN->inputNumber();
ptrN->displayNumber();
return 0;
}
Output
输出量
Enter an integer number: 10
Num: 10
Default value...
Num: 0
Enter an integer number: 20
Num: 20
Explanation:
说明:
The main three steps needs to be understood those are:
需要理解的主要三个步骤是:
Pointer to object creation: Number *ptrN;
指向对象创建的指针: Number * ptrN;
Dynamic memory initialization to the pointer object: ptrN = new Number;
指针对象的动态内存初始化: ptrN = new Number;
Accessing member function by using "Arrow Operator": ptrN->displayNumber();
通过使用“箭头运算符”访问成员函数: ptrN-> displayNumber();
翻译自: https://www.includehelp.com/cpp-programs/accessing-member-function-by-pointer.aspx
c ++ 函数的esp指针