MyException - 我的异常网
当前位置:我的异常网» C++ » C++学习札记(五)- 成员指针

C++学习札记(五)- 成员指针

www.myexceptions.net  网友分享于:2013-04-10  浏览:0次
C++学习笔记(五)-- 成员指针

c++不仅支持指针 还添加了新的指针
 int A::*p = &A::m; //成员指针

用法

 A a; a.*p;

  A *pa = new A; a->*p;


 void (A::*f)() = &A::func; //成员函数指针
用法
A a; (a.*p)();

A *pa; (a->*p)();

struct Date
{
	int year;
	int month;
	int day;
	void print()
	{
		cout << year<<"-"<<month<<"-"<<day<<endl;
	}
};

void showmember(Date a[],int n,int Date::*p)
{

	for(int i = 0; i < n;i++)
	{
		cout << a[i].*p << " ";
	//	cout << (a+i)->*p << " ";
	} 
	cout << endl;
}
int main()
{
	Date a[5]={{2010,8,16},{2010,10,1},{2012,12,20},
		{1999,12,30},{2013,4,5}};
	Date d = {1997,9,10};

	//C++中 函数地址和成员地址 都会被初始化为true  
//	cout << reinterpret_cast<int>(&Date::year) << endl; 
//member.cpp:27: error: invalid cast from type ‘int Date::*’ to type ‘int’

	cout << &Date::year << endl; //1
	cout << &main <<" " <<main << endl; //1 1


	//定义成员指针
	int Date::*mp = &Date::month;
	cout << d.*mp	 << endl; //9
	mp = &Date::year;
	cout <<  d.*mp << endl; //1997  .*当作一个运算符

	showmember(a,5,&Date::month);
	showmember(a,5,&Date::year);
	
	d.print();

	//成员函数指针
	void (Date::*pf)() = &Date::print;
	(d.*pf)();
}


另外附上关于参数个数的小知识:

#include <iostream>
using namespace std;
//c++中无参和void一样
void f1(){cout << "hello" << endl;}
void f2(void){return f1();}
int main()
{
//	f2(123);
//	报错error: too many arguments to function ‘void f2()
//	这点里C放参数虽也没有作用,但不会报错。 在C++中会报错。
	f1();
	f2();
}



文章评论

软件开发程序错误异常ExceptionCopyright © 2009-2015 MyException 版权所有