六種不同指標的使用方法

來源:互聯網
上載者:User

//本程式用來區別下面六種指標:1.普通指標  2.普通函數指標  3.指向類的資料成員的指標
//4.指向類的成員函數的指標  5.指向類的待用資料成員的指標  6.指向類的靜態成員函數的指標

#include<iostream>
#include<string>
using namespace std;

class  Myclass
{
public:
 Myclass(int i=0,int j=0 ):_weight(i),_height(j){}
 void  print()
 {
  cout<<_weight<<","<<_height<<","<<the_same<<endl;
 }

 static   void modifythesame(int xx)
 {
  the_same=xx;
 }//靜態成員函數只能修改待用資料成員
public:
 int _weight,_height;
 static the_same;
};

int Myclass::the_same=0;

int max(int a,int b)
{return a<b? b:a;
}

int a=2,b=3;
Myclass myclass;

int *p1=&a;                          //第一種:普通指標
int (*p2)(int ,int )=max;            //第二種:普通函數指標
int  Myclass::*p3=&Myclass::_height ;//第三種指標:指向類的資料成員的指標,與普通
                                     //的指標的區別在於左右兩邊要加上:類名::
void  (Myclass::*p4)()=&Myclass::print;//第四種指標:指向類的成員函數的指標,與普通
                                       //的函數指標的區別也是在左右兩邊加上:類名::
int *p5=&Myclass::the_same;//第五種指標:指向類的待用資料成員的指標,左邊是普通指標
                           //一樣,右邊要加上:類名::
void (*p6)(int)=&Myclass::modifythesame;// 第六種指標:指向類的靜態成員函數的指標
                                        //左邊與普通函數指標一樣,右邊要加上:類名::

void main()
{
  cout<<*p1<<endl;//第一種普通指標的使用
  cout<<p2(a,b)<<endl;//第二種普通函數指標的使用
  cout<<myclass.*p3<<endl;//第三種指向類的資料成員的指標的使用,將原來的資料成員名用
                          //*P代替即可
  (myclass.*p4)();//第四種指向類的成員函數的指標的使用,將原來的成員函數名用*p代替,並且
                  //要用()括起來,這個地方容易忘記
  cout<<*p5<<endl;//第五種指向類的待用資料成員的指標的使用,同普通指標的使用
  p6(a);          //第六種指向類的靜態成員函數的指標的使用,同普通函數指標的使用
  cout<<*p5<<endl;
}

 

/*犯的錯誤是:
(1)第四種指標的使用的時候沒有加();
(2)當時將_weight定義為private,導致了cout<<myclass.*p3<<endl;沒有辦法訪問私人成員
*/

 

 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.