姓名:郭君牧 学号:25020042014 专业年级:2025级海洋技术
指导教师:田丰林 实验日期:11月18日
1.练习通过 debug 观察指针的内容及其所指的对象的内容;
2.练习通过动态内存分配实现动态数组,并体会指针在其中的作用;
3.分别使用字符数组和标准 C++ 库练习处理字符串的方法。
1.指针作为函数参数;
2.指针与数组:数组的地址、指针与一维数组、指针与二维数组、指针数组。
//6_16.cpp
#include <iostream>
using namespace std;
class Point {
public:
Point() : x(0), y(0) {
cout<<"Default Constructor called."<<endl;
}
Point(int x, int y) : x(x), y(y) {
cout<<"Constructor called."<<endl;
}
~Point() {cout<<"Destructor called."<<endl;}
int getX() const {return x;}
int getY() const {return y;}
void move(int newX, int newY) {
x=newX;
y=newY;
}
private:
int x, y;
};
int main() {
cout<<"Step one: "<<endl;
Point *ptr1=new Point; //动态创建对象,没有参数列表,调用默认构造函数
delete ptr1; //删除对象,自动调用析构函数
cout<<"Step two: "<<endl;
ptr1=new Point(1,2); //动态创建对象,调用有形参的构造函数
delete ptr1; //删除对象,自动调用析构函数
return 0;
}
图 1 例题 6-16 源程序
//6_17.cpp
#include <iostream>
using namespace std;
class Point {
public:
Point() : x(0), y(0) {
cout<<"Default Constructor called."<<endl;
}
Point(int x, int y) : x(x), y(y) {
cout<<"Constructor called."<<endl;
}
~Point() {cout<<"Destructor called."<<endl;}
int getX() const {return x;}
int getY() const {return y;}
void move(int newX, int newY) {
x=newX;
y=newY;
}
private:
int x, y;
};
int main() {
Point *ptr=new Point[2]; //创建对象数组
ptr[0].move(5, 10); //通过指针访问数组元素的成员
ptr[1].move(15, 20); //通过指针访问数组元素的成员
cout<<"Deleting..."<<endl;
delete[] ptr; //删除整个对象数组
return 0;
}
图 2 例题 6-17 源程序
//6_18.cpp
#include <iostream>
#include <cassert>
using namespace std;
class Point {
public:
Point() : x(0), y(0) {
cout<<"Default Constructor called."<<endl;
}
Point(int x, int y) : x(x), y(y) {
cout<<"Constructor called."<<endl;
}
~Point() {cout<<"Destructor called."<<endl;}
int getX() const {return x;}
int getY() const {return y;}
void move(int newX, int newY) {
x=newX;
y=newY;
}
private:
int x, y;
};
//动态数组类
class ArrayOfPoints {
public:
ArrayOfPoints(int size) : size(size) {
points = new Point[size];
}
//这里没有定义复制构造函数是有问题的
~ArrayOfPoints() {
cout<<"Deleting..."<<endl;
delete[] points;
}
//获得下标为 index 的数组元素
Point &element(int index) {
assert(index >= 0 && index < size); //下标越界则程序中止
return points[index];
}
private:
Point *points; //指向动态数组首地址
int size; //数组大小
};
int main() {
int count;
cout<<"Please enter the count of points: ";
cin>>count;
ArrayOfPoints points(count); //创建对象数组
points.element(0).move(5, 0);
points.element(1).move(15, 20);
return 0;
}
图 3 例题 6-18 源程序
//6_20.cpp
#include <iostream>
#include <vector>
using namespace std;
//计算数组 arr 中元素的平均值
double average(const vector<double>& arr) {
double sum = 0;
for (unsigned i = 0; i < arr.size(); i++)
sum += arr[i];
return sum / arr.size();
}
int main() {
unsigned n;
cout << "n=";
cin >> n;
vector<double> arr(n); //创建数组对象
cout << "Please input " << n << " real numbers:" << endl;
for (unsigned i = 0; i < n; i++)
cin >> arr[i];
cout << "Average=" << average(arr) << endl;
return 0;
}
图 4 例题 6-20 源程序
//6_21.cpp
#include <iostream>
#include <cassert>
using namespace std;
class Point {
public:
Point() : x(0), y(0) {
cout<<"Default Constructor called."<<endl;
}
Point(int x, int y) : x(x), y(y) {
cout<<"Constructor called."<<endl;
}
~Point() {cout<<"Destructor called."<<endl;}
int getX() const {return x;}
int getY() const {return y;}
void move(int newX, int newY) {
x=newX;
y=newY;
}
private:
int x, y;
};
class ArrayOfPoints {
public:
ArrayOfPoints(int size) : size(size) {
points = new Point[size];
}
~ArrayOfPoints() {
cout<<"Deleting..."<<endl;
delete[] points;
}
Point &element(int index) {
assert(index >= 0 && index < size);
return points[index];
}
private:
Point *points;
int size;
};
int main() {
int count;
cout << "Please enter the count of points: ";
cin >> count;
ArrayOfPoints pointsArray1(count); //创建对象数组
pointsArray1.element(0).move(5,10);
pointsArray1.element(1).move(15,20);
ArrayOfPoints pointsArray2 = pointsArray1; //默认浅拷贝
cout << "Copy of pointsArray1:" << endl;
cout << "Point_0 of array2: " << pointsArray2.element(0).getX() << ", "
<< pointsArray2.element(0).getY() << endl;
cout << "Point_1 of array2: " << pointsArray2.element(1).getX() << ", "
<< pointsArray2.element(1).getY() << endl;
pointsArray1.element(0).move(25, 30);
pointsArray1.element(1).move(35, 40);
cout << "After the moving of pointsArray1:" << endl;
cout << "Point_0 of array2: " << pointsArray2.element(0).getX() << ", "
<< pointsArray2.element(0).getY() << endl;
cout << "Point_1 of array2: " << pointsArray2.element(1).getX() << ", "
<< pointsArray2.element(1).getY() << endl;
return 0;
}
图 5 例题 6-21 源程序
//6_22.cpp
#include <iostream>
#include <cassert>
using namespace std;
class Point {
public:
Point() : x(0), y(0) {
cout<<"Default Constructor called."<<endl;
}
Point(int x, int y) : x(x), y(y) {
cout<<"Constructor called."<<endl;
}
~Point() {cout<<"Destructor called."<<endl;}
int getX() const {return x;}
int getY() const {return y;}
void move(int newX, int newY) {
x=newX;
y=newY;
}
private:
int x, y;
};
class ArrayOfPoints {
public:
ArrayOfPoints(int size) : size(size) {
points = new Point[size];
}
ArrayOfPoints(const ArrayOfPoints& v); //深拷贝复制构造函数声明
~ArrayOfPoints() {
cout<<"Deleting..."<<endl;
delete[] points;
}
Point &element(int index) {
assert(index >= 0 && index < size);
return points[index];
}
private:
Point *points;
int size;
};
//深拷贝复制构造函数实现
ArrayOfPoints::ArrayOfPoints(const ArrayOfPoints& v) {
size = v.size;
points = new Point[size];
for (int i = 0; i < size; i++)
points[i] = v.points[i];
}
int main() {
int count;
cout << "Please enter the count of points: ";
cin >> count;
ArrayOfPoints points1(count);
points1.element(0).move(5, 0);
points1.element(1).move(15, 20);
ArrayOfPoints points2 = points1; //调用深拷贝复制构造函数
cout << "Copy finished." << endl;
return 0;
}
图 6 例题 6-22 源程序
//6_23.cpp
#include <string>
#include <iostream>
using namespace std;
//根据 value 的值输出 true 或 false,title 为提示文字
inline void test(const char * title, bool value) {
cout << title << " returns " << (value ? "true" : "false") << endl;
}
int main() {
string s1 = "DEF";
cout << "s1 is " << s1 << endl;
string s2;
cout << "Please enter s2: ";
cin >> s2;
cout << "length of s2: " << s2.length() << endl;
//比较运算符的测试
test("s1 <= \"ABC\"", s1 <= "ABC");
test("\"DEF\" <= s1", "DEF" <= s1);
//连接运算符的测试
s2 += s1;
cout << "s2=s2+s1: " << s2 << endl;
cout << "length of s2: " << s2.length() << endl;
return 0;
}
图 7 例题 6-23 源程序
//Rectangle.h
#ifndef RECTANGLE_H
#define RECTANGLE_H
class Rectangle {
public:
void initRectangle(int x, int y, int w, int h) {
this->x = x;
this->y = y;
this->w = w;
this->h = h;
}
void move(int newX, int newY) {
x = newX;
y = newY;
}
int getX() const { return x; }
int getY() const { return y; }
int getW() const { return w; }
int getH() const { return h; }
private:
int x = 0, y = 0, w = 0, h = 0;
};
#endif
//7_1.cpp
#include <iostream>
#include <cmath>
#include "Rectangle.h"
using namespace std;
int main() {
Rectangle rect; //定义 Rectangle 类的对象
rect.initRectangle(2, 3, 20, 10); //设置矩形的数据
rect.move(3, 2); //移动矩形位置
cout << "The data of rect(x,y,w,h): " << endl;
cout << rect.getX() << ", " //输出矩形的特征参数
<< rect.getY() << ", "
<< rect.getW() << ", "
<< rect.getH() << endl;
return 0;
}
图 8 例题 7-1 源程序及 Rectangle.h
//exp1.cpp
#include <iostream>
#include <cstring>
using namespace std;
//递归函数:将 s 及其后面的内容原地倒序
void reverse(char *s)
{
int len = static_cast<int>(strlen(s));
if (len <= 1) //递归终止条件:空串或只有一个字符
return;
char first = s[0]; //暂存首字符
s[0] = s[len - 1]; //首尾字符交换
s[len - 1] = '\0'; //截掉末尾,只保留中间部分
reverse(s + 1); //递归倒序中间部分
s[len - 1] = first; //把原首字符补到末尾
}
int main()
{
char str[100];
cout << "Please enter a string: ";
cin.getline(str, 100);
reverse(str);
cout << "Reversed: " << str << endl;
return 0;
}
图 9 实验一源程序
//exp2.cpp
#include <iostream>
#include <cctype>
using namespace std;
int countLetters(const char *s)
{
int cnt = 0;
while (*s != '\0')
{
if (isalpha(static_cast<unsigned char>(*s)))
++cnt;
++s; //指针后移,指向下一个字符
}
return cnt;
}
int main()
{
char text[1000];
cout << "Please enter an English sentence: ";
cin.getline(text, 1000); //可以读入含空格的整句
cout << "Number of letters: " << countLetters(text) << endl;
return 0;
}
图 10 实验二源程序
//exp3.cpp
#include <iostream>
#include <string>
using namespace std;
class Employee
{
public:
Employee(const string &n = "", const string &st = "",
const string &c = "", const string &pc = "")
: name(n), street(st), city(c), postcode(pc) {}
void change_name(const string &newName) //修改姓名属性
{
name = newName;
}
void display() const //显示各属性,不修改对象
{
cout << "Name : " << name << endl;
cout << "Street : " << street << endl;
cout << "City : " << city << endl;
cout << "Postcode: " << postcode << endl;
}
private:
string name;
string street;
string city;
string postcode;
};
int main()
{
Employee emp("GuoJunmu", "238 Songling Road", "Qingdao", "266100");
cout << "==== Before change ====" << endl;
emp.display();
emp.change_name("Junmu Guo");
cout << "\n==== After change ====" << endl;
emp.display();
return 0;
}
图 11 实验三源程序
实验一运行结果:
Please enter a string: abcdef Reversed: fedcba
图 12 实验一运行结果
实验二运行结果:
Please enter an English sentence: Hello, C++ World! 2026 Number of letters: 11
图 13 实验二运行结果
实验三运行结果:
==== Before change ==== Name : GuoJunmu Street : 238 Songling Road City : Qingdao Postcode: 266100 ==== After change ==== Name : Junmu Guo Street : 238 Songling Road City : Qingdao Postcode: 266100
图 14 实验三运行结果
例题 6-16 依次输出 Default Constructor called.、Destructor called. 与 Constructor called.、Destructor called.,验证了 new 创建对象时调用构造函数、delete 删除对象时调用析构函数;6-17 中 delete[] 删除对象数组时两个元素的析构函数都被调用;6-20 输入 5 个数后输出正确的平均值;6-21 中 pointsArray1 移动后 pointsArray2 的坐标随之改变,说明默认复制构造函数为浅拷贝;6-23 中 s2 连接 s1 后长度由 3 变为 6。
本次上机实验围绕指针、动态内存分配、字符串处理和类与对象展开,完成了字符串递归倒序、统计英文字母个数、Employee 类的设计与测试三个实验,并调试运行了课本 6-16 至 7-1 的多个例题,加深了对指针、数组、字符串和面向对象基础的理解。
实验一中 reverse 函数采用“先递归、后回溯”的结构:递归调用前交换首尾字符并用 '\0' 截断末尾,递归返回后再把暂存的首字符补到末尾,从而在不额外开辟数组的情况下完成原地倒序,体会到递归与指针配合的简洁之处。实验二用指针自增遍历字符数组,验证了数组名可看作指向首元素的指针、*s 与 s[0] 等价,同时认识到读入含空格的整句必须用 cin.getline(),而不能用 cin >>。实验三体会到类的封装性:数据成员置于 private,外部只能通过公有成员函数访问;change_name() 只修改姓名,display() 声明为 const 以保证不改变对象状态。
通过调试例题还认识到,new 与 delete、new[] 与 delete[] 必须配对使用,否则会造成内存泄漏;没有自定义复制构造函数时,对象数组的复制只是浅拷贝,两个对象会共享同一块动态内存,析构时重复释放而出错,6-22 的深拷贝复制构造函数正好解决了这一问题。今后还需加强二维数组指针、指针数组与动态数组的综合练习,养成单步调试观察内存、检查边界条件的编程习惯。