重庆邮电大学计算机学院C++上机试验报告 下载本文

内容发布更新时间 : 2024/5/2 13:11:49星期一 下面是文章的全部内容请认真阅读。

C++集中上机实验日志

实验6—1

一、问题描述

定义一个字符串类String,其数据成员有指向字符串的指针elems,成员函数包括构造函数、析构函数、判断字符串是否为空的operator!()。编程测试类String的功能。 二、实验输出

如图所示:

三、实验思路以及方法

判断字符串是否为空即是对字符串进行非运算,即重载operator!()。逻辑非运算是单目运算符,按照运算符重载方针,应该重载为类的成员函数。由于逻辑非运算结果只有两种:真、假,因此operator!()的返回值类型为bool型。 四心得体会

开始没有判断elems的空指针问题,遇到一点麻烦,改过之后就ok了,本实验让我们学习了“运算符重载类的成员函数”,对以后

的学习C++有了很大了帮助。 代码实现

#include #include using namespace std; class String {

public:

String(const char *e=NULL); ~String();

bool operator!()const; private:

char *elems; };

String::String (const char *e) {

if(e==NULL) { elems=NULL; return; } else {

elems=new char[strlen(e)]; strcpy(elems,e); return; } }

bool String::operator !()const {

if(elems==NULL)return true; else return false; }

String::~String () {

if(elems!=NULL) delete[]elems; }

int main() {

String str; if(!str)

cout<<\这是一个空字符串!\ return 0; }

实验6-3

一、问题重述

对于具有相同行列数的矩阵进行加、减、乘、转置、赋值运算。 二、实验输出 结果如图所示:

三、实现思路及方法

定义矩阵类Matrix,他的数据成员有:行line、列col、指向矩阵元素的指针int*elems。他的成员函数有:构造函数、析构函数、复制构造函数、一组读取和修改属性的get、set方法、显示矩阵元素的方法print()。还需要对Matrix类的重载运算符:

Matrix operator+(const Matrix &a,const Matrix &b);

Matrix operator-(const Matrix &a,const Matrix &b); Matrix operator*(const Matrix &a,const Matrix &b); Matrix operator=(const Matrix &m); Matrix operator~()const;

四、心得体会

这次对友元的初次使用,感觉到很陌生,在对数组处理的时候有很大的错误,对空间的申请和判断是否为空上面存在很大的问题,但是也学到了很多东西,比如说:友元可以是一个全局函数,也可以是一个类的成员函数,还可以是一个类,如果友元是函数,则称为友元函数,如果友元是一个类,则称为友元类,友元的所有成员函数都是友元函数,可以访问被访问类的所有成员。 代码实现

#include #include #include using namespace std; class Matrix;

Matrix operator+(const Matrix &a,const Matrix &b); Matrix operator-(const Matrix &a,const Matrix &b); Matrix operator*(const Matrix &a,const Matrix &b); class Matrix {

friend Matrix operator+(const Matrix &a,const Matrix &b); friend Matrix operator-(const Matrix &a,const Matrix &b); friend Matrix operator*(const Matrix &a,const Matrix &b); public:

Matrix(int l,int c);

Matrix(const Matrix &m); ~Matrix();

void setLine(int l); void setCol(int c);

void setElems(); int getLine()const; int getCol()const; void print()const;

Matrix operator=(const Matrix &m); Matrix operator~()const;

private: int line; int col; int *elems; };

Matrix operator+(const Matrix &a,const Matrix &b) {

if(a.line != b.line || a.col != b.col) {

cerr << \两矩阵的行列数不相同!\ exit(EXIT_FAILURE); }

Matrix temp(a.line,a.col);

for(int i = 0;i < a.line * a.col;i++) temp.elems[i] = a.elems[i] + b.elems[i]; return temp; }

Matrix operator-(const Matrix &a,const Matrix &b) {

if(a.line != b.line || a.col != b.col) { cerr << \两矩阵的行列数不相同!\ exit(EXIT_FAILURE); }

Matrix temp(a.line,a.col); for(int i = 0;i < a.line * a.col;i++) temp.elems[i] = a.elems[i] - b.elems[i]; return temp; }

Matrix operator*(const Matrix &a,const Matrix &b) {

if(a.col != b.line ) { cerr << \第一个矩阵的列数和第二个矩阵的行数不相同!\ exit(EXIT_FAILURE);