实验4 析构函数 对象数组与指针
2017-10-29 22:32
423 查看
#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的地址, 而非数组的地址
/
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的地址, 而非数组的地址
/
相关文章推荐
- C++学习笔记(六)-- 类和对象 构造函数和析构函数 const成员函数 this指针 对象数组 堆栈管理变量
- 对象数组,对象指针,常对象、对象的常引用
- 第八讲:对象数组与指针
- 基类指针指向子类对象数组的问题
- C++对象数组调用构造/析构函数的方法
- 若使用基类指针delete派生类对象,需将基类和派生类的析构函数声明为virtual
- 对象数组和指向对象的指针 指向类成员的指针
- 指向自由存储区中对象的指针数组
- C++通过基类指针delete派生类数组,析构函数是虚函数,程序为什么会崩溃? https://www.zhihu.com/question/30838092/answer/49623765
- C++ 学习之路(2):对象数组和指针
- 二十六、数组、指针和字符串:数组的存储与初始化、对象数组、数组作为函数参数
- 建立一个对象数组,内放5个学生数据(学号、成绩),用指针指向数组首元素,输出学生的数据
- 析构函数和对象数组和对象指针
- 关于通过不含虚析构函数的基类类型的指针删除派生类对象的问题
- 关于基类指针指向子类对象,构造函数和析构函数调用的顺序的问题。
- [C++对象模型][3]指针与数组
- C++之对象数组和对象指针
- 指针和对象的数组实现
- 4,17建立对象数组,存放6个学生数据,指针指向数组首个元素,输出2,4,6个学生数据
- 计算机程序设计(C++)第10周编程作业数据的抽象和封装——类(2)——构造函数、析构函数和指向对象的指针