c ++ 函数的esp指针_在C ++中通过指针访问成员函数
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://constructorNumber(){ num=0; };//member function to get inputvoid 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 numberNumber N;//input and display number using norn objectN.inputNumber();N.displayNumber();//declaring pointer to the object Number *ptrN;ptrN = new Number; //creating & assigning memory //printing default valuecout<<"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: 20Explanation:
說明:
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指針
總結
以上是生活随笔為你收集整理的c ++ 函数的esp指针_在C ++中通过指针访问成员函数的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: doublevalue_Java Dou
- 下一篇: C程序生成一定范围内的随机数