1.类和对象
①.类:Student
对象:s1,s2
②.类的一般形式
class Student
{
private: 数据成员、成员函数声明;
public: 数据成员、成员函数声明;
(protected:)数据成员、成员函数声明;
};
<成员函数的实现代码>
2.成员的访问权限
①.公有,私有,保护
②.未声明哪一类,默认权限为private:
3.访问对象(s1、s2 或 *p )的成员
①.对象名.函数名;s1.disp();
②.指针变量->函数名; p->disp();
int main()
{
Student s1, *p;
p = &s1;
s1.set(001, "李华");
s1.disp();
p->disp();
}
4.堆对象
①.用new 运算符创建 堆对象,delete 运算符删除 堆对象
②.如,类Example
Example *p; //定义指向类Example的指针p
p = new Example();//使用new 给p分配内存空间
delete p; //使用delete 释放p指向的空间
③.堆对象的生存期为,整个程序的生命期
#include <iostream>
using namespace std;
class Sample
{
private:
int x;
int y;
public:
void get(int a,int b)
{
x=a;
y=b;
}
void disp();
};
void Sample::disp()
{
cout<<"x="<<x<<" y="<<y<<endl;
}
int main()
{
Sample *p;
p=new Sample[3];
p[0].get(1,2);
p[1].get(3,4);
p[2].get(5,6);
for(int i=0;i< 3;i++)
p[i].disp();
delete[] p;
}
p0,p1,p2为地址连续的指针
5.this指针