代码改变世界

《C++必知必会》读书笔记3

2012-03-25 12:45  Rollen Holt  阅读(391)  评论(0编辑  收藏  举报

指向数据成员的“指针”并非指针。

#include <iostream>
using namespace std;

class A{
public:
	A(){
		//do nothing here.
	}
	A(int num,double num2){
		this->num=num;
		this->num2=num2;
	}
	int num;
	double num2;
};

int _tmain(int argc, _TCHAR* argv[])
{	
	A* pA=new A(5,6);

	int A::* p=&A::num;  //p是一个指针,指向A的一个int成员
	double A::*p1=&A::num2;
	cout<<p<<endl;   //输出偏移量 而不是地址
	cout<<p1<<endl;

	//通过偏移量访问数据成员
	cout<<pA->*p<<endl;
	cout<<pA->*p1<<endl;

	delete pA;
	return 0;
}

image

指向成员函数的指针并非指针:

#include <iostream>
using namespace std;

class A{
public:
	void function( int num);
	bool function1()const;
	virtual bool function2() const=0;
};

class B:public A{
public :
	bool function2()const;
};

int _tmain(int argc, _TCHAR* argv[])
{	
	void (A::* p)(int)= &A::function;  //不是地址,而是一个指向成员函数的指针
	
	bool (A::* p1)()const =&A::function1;  // 指向成员函数的指针可以指向一个常量成员函数

// 	B b;
// 	A *a=&b;
// 	(a->*p1)();
// 	(b.*p1)();

	return 0;
}