类成员的指针

来源:互联网 发布:青岛学淘宝美工 编辑:程序博客网 时间:2024/05/29 12:31

psconst对象只能调用const函数!!非const对象随便!!

 

成员指针只应用于类的非 static成员。static 类成员不是任何对象的组成部分,所以不需要特殊语法来指向 static成员,static成员指针是普通指针

int *p = &Screen::total;   (total static int total;)

 

例子:

#include<iostream>

using namespace std;

class Screen{

public:

       static int total;

       int sum;

       Screen():sum(2){}

       int a(int i, int j){

              cout<<244<<endl;

              return 8;

       }

};

int Screen::total = 6;

int main(){

       Screen sc;

      int *ptr = &Screen::total;

int Screen::*p1 = &Screen::sum;

int (Screen::*p2)(int, int) = &Screen::a;

      cout<<sc.*p1<<"**"<<sc.total<<"**"<<(sc.*p2)(1,2)<<endl;

cout<<*ptr<<endl;

       return 0;

}

输出:

244     ----------先出来

2**6**8

 

 

l  声明成员指针

class Screen {

public:

typedef std::string::size_type index;

char get() const;

char get(index ht, index wd) const;

private:

std::string contents;

index cursor;

index height, width;

};

ü  定义数据成员的指针

contents

string Screen::*ptr = &Screen::contents;

Screen::indexScreen::*p = &Screen::cursor;

 

ü  定义成员函数的指针

成员函数的指针必须在三个方面与它所指函数的类型相匹配:

1.函数形参的类型和数目,包括成员是否为 const

2.返回类型。

3.所属类的类型。

 

get()

char (Screen::*p)()const = &Screen::get;

char (Screen::*p)(Screen::index,Screen::index)const = &Screen::get;

 

ü  为成员指针使用类型别名

typedef char (Screen::*Action)(Screen::index, Screen::index) const;

Action p = &Screen::get;

 

l  使用类成员指针

 成员指针解引用操作符(.*)从对象或引用获取成员。  

ps:不能重载的操作符(:: .  .*  ?:

必须成员函数([]  ()  ->

必须友元(<<  >>

 成员指针箭头操作符(->*)通过对象的指针获取成员。

 

ü  使用成员函数指针

char (Screen::*pmf)() const = &Screen::get;

Screen myScreen;

char c1 = myScreen.get();

char c2 =(myScreen.*pmf)(); // equivalent call to get

Screen *pScreen = &myScreen;

c1 = pScreen->get();

c2 = (pScreen->*pmf)(); // equivalent call to get

 

因为调用操作符(())比成员指针操作符优先级高,所以调用(myScreen.*pmf)() (pScreen->*pmf)() 需要括号。

 

ü  使用数据成员指针

Screen::index Screen::*pindex = &Screen::width;

Screen myScreen;

Screen::index ind1 = myScreen.width;

Screen::index ind2 = myScreen.*pindex; // dereference to get width

Screen *pScreen;

ind1 = pScreen->width;

ind2 = pScreen->*pindex;// dereference pindex to get width

ps:不要加括号!!!

 

****************成员函数的指针不同与普通函数的指针************

 

成员函数的指针:

char (Screen::*pmf)() const = &Screen::get;    //必须有&

使用是(myScreen.*pmf)() 或者(pScreen->*pmf)()

 

普通函数的指针:

char (*pmf)() const = &get;  或者   char (*pmf)() const =get;

使用是 pmf()  或者 (*pmf)()

0 0