c++函数指针,动态内存分配,对象指针

对象指针

#include <iostream>
using namespace std;
class Point {
public:
	Point():x(0),y(0){ cout << "调用默认构造函数" << endl; }
	Point(int x1,int y1) :x(x1), y(y1) { cout << "调用含参构造函数" << endl; }
	~Point() 
	{ 
		cout << "调用析构函数" << endl; 
	}
	int getX() const{ return x; }//const函数,说明该函数不改变私有数据成员
	int getY() const { return y; }
private:
	int x, y;
};

int main()
{
	/*一般初始化对象指针*/
	Point *pb;
	Point b; //调用默认构造函数
	pb = &b;
	cout << "b.x=" << pb->getX() << endl;//可通过指针也可通过对象名访问
	cout << "b.y=" << b.getY() << endl;
	Point *pa;
	Point a(3, 4);//调用含参构造函数
	pa = &a;//等同于Point *po = &a;
	cout << "a.x=" << pa->getX() << endl;
	cout << "a.y=" << a.getY() << endl;

	/*动态内存分配new,初始化对象指针*/
	Point *p1;
	p1=new Point;//返回的是Point类对象的指针,调用默认构造函数
	cout << "p1.x=" << p1->getX() << endl;//只能通过指针因为没有对象名
	cout << "p1.x=" << p1->getY() << endl;
	delete p1;
	Point *p2;
	p2 = new Point(4,5);//调用含参构造函数
	cout << "p2.x=" << p2->getX() << endl;//只能通过指针因为没有对象名
	cout << "p2.y=" << p2->getY() << endl;
	delete p2;
	return 0;
}

运行结果:

调用默认构造函数
b.x=0
b.y=0
调用含参构造函数
a.x=3
a.y=4
调用默认构造函数
p1.x=0
p1.x=0
调用析构函数
调用含参构造函数
p2.x=4
p2.y=5
调用析构函数
调用析构函数
调用析构函数
请按任意键继续. . .

函数指针

#include <iostream>
using namespace std;
int conpute(int a,int b,int (*pf)(int,int))
{
	return pf(a,b);//函数指针名当被指函数名使用
}
int Sum(int a, int b)
{
	return a+b;
}
int Max(int a, int b)
{
	return a > b ? a : b;
}
int Min(int a, int b)
{
	return a < b ? a : b;
}int main()
{
	cout<<"Max((3, 5)="<<conpute(3, 5, Max)<<endl;//函数名代表函数入口地址,就像数组名代表数组首元素地址
	cout << "Min((3, 5)=" << conpute(3, 5, Min) << endl;
	cout << "Sum(3, 5)=" << conpute(3, 5, Sum) << endl;
	cout << "——————分界线——————" << endl;
	cout << "Max((3, 5)=" << conpute(3, 5, &Max) << endl;//也可以对函数名取地址
	cout << "Min((3, 5)=" << conpute(3, 5, &Min) << endl;
	cout << "Sum(3, 5)=" << conpute(3, 5, &Sum) << endl;

	return 0;
}

运行结果:

Max((3, 5)=5
Min((3, 5)=3
Sum(3, 5)=8
——————分界线——————
Max((3, 5)=5
Min((3, 5)=3
Sum(3, 5)=8
请按任意键继续. . .
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值