快捷搜索: 王者荣耀 脱发

实验4 析构函数 对象数组与指针

#include<iostream>
using namespace std;
class student
{
private:
int num;
int score;

public:
student(int n=0, int s=0) :num(n), score(s){}  //定义带参数的构造函数//用参数初始化表对数据成员进行初始化
~student()                                     //定义析构函数
{
cout << "clear!" << endl;
}
void display(student * p);
};
void student::display(student * p)
{
cout << "学生1:" << " 学号 " << " 分数 " << endl;
cout << "        " << p[0].num <<"    "<< p[0].score << endl;
cout << "学生3:" << " 学号 " << " 分数 " << endl;
cout << "        " << p[2].num << "    " << p[2].score << endl;
cout << "学生5:" << " 学号 " << " 分数 " << endl;
cout << "        " << p[4].num << "    " << p[4].score << endl;
}
int main()
{
student arry[5] = { student(2010, 95), student(2011, 96), student(2012, 97), student(2013, 98), student(2014, 99) };
student *p;                                   //定义指向student类的指针
p = arry;                                     //p指针等于arry指针,p指向数组arry[5]的首地址
(*p).display(p);
return 0;
}

//p=arry 等价于 p=&arry[0]

//arry本身是一个指针,其指向对象数组名为arry的首地址。(arry另外有属于自己的空间)小括号为自己的理解,有错误请指正

具体讲: 可以认为arry这个变量中放的是数组的首地址,即数组第一个元素的地址, arry(数组名)本身占一个(char*),“指向char类型的指针”, 那么p=&arry实际上是取的a的地址, 而非数组的地址


/
经验分享 程序员 微信小程序 职场和发展