对象指针
#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
请按任意键继续. . .