一、实训目的
(1)掌握指针数组及指向数组指针用法。
(2)掌握对象指针、this指针、指向类成员的指针的用法。
二、实训内容
(1)编写满以下功能要求的C++源代码(可以将实验功能要求中的所有功能编 写到一个程序中,也可以针对不同的功能编写不同的程序代码)。
(2)调试运行。
(3)记录运行结果并进行分析,撰写实验报告。
三、实训所实现系统主要功能
(1)编写程序,使用一维指针数组来读写二维数组数据 ,并与普通二维数组直接读写数据的结果进行比较。
(2)编写具有一定功能的简单程序,要求用到对象指针、this指针、指向类成员的指针(包含类普通数据成员、函数成员以及静态数据成员、函数成员)等语法机制。
四、实训系统核心代码及必要说明
#include<iostream>
#include<algorithm>
#include<cstdio>
#include<cstring>
using namespace std;
class People {
private:
string name;
int age;
static int count;
public:
string sex;
People(string name, int age, string sex) {
this->name = name;
this->age = age;
this->sex = sex;
count++;
}
void showmessaage() {
cout << "姓名:" << name << " 年龄:" << age << endl;
}
static int showcount() {
cout << "当前类中人的总数为:" << count << endl;
return count;
}
~People() {
count--;
}
};
int People::count = 0;
int main() {
char s[100][100];
//普通二维数组直接读写
cout << "普通二维数组直接读写" << endl;
for (int i = 0; i < 3; i++)
for (int j = 0; j < 5; j++) cin >> s[i][j];
for (int i = 0; i < 3; i++)
{
for (int j = 0; j < 5; j++) cout << s[i][j];
cout << endl;
}
//一维指针数组来读写二维数组数据
cout << "一维指针数组来读写二维数组数据" << endl;
for (int i = 0; i < 3; i++) cin >> s[i];
for (int i = 0; i < 3; i++) cout << s[i] << endl;
//对象数组
People p[2] = { People("猪猪侠", 18, "男"), People("菲菲公主", 18, "女") };
cout << p ->sex << " " << (p + 1) ->sex << endl;
//指向数据成员的指针
string People::* ss = &People::sex;
cout << p[0].*ss << " " << p[1].*ss << endl;
//指向成员函数的指针
void (People:: *aa)();
aa = &People::showmessaage;
(p[0].*aa)();
(p[1].*aa)();
int(*bb)() = &People:: showcount;
bb();
return 0;
}
五、实训结果截图及分析