①.利用new和delete实现一个二维数组,存放浮点数,实现矩阵的加法运算,并输出数据; ②.构造一个struct结构 struct student{ int num, string name, char sex };要求使用new和delete操作该struct,并输出数据。
时间: 2024-10-28 20:09:12 浏览: 5
利用MFC实现简单的矩阵运算
4星 · 用户满意度95%
①. 实现一个二维数组和矩阵加法运算:
```cpp
#include <iostream>
// 定义一个二维浮点数数组
class Matrix {
public:
int rows, cols;
float** data;
// 构造函数,分配内存
Matrix(int r, int c) : rows(r), cols(c) {
data = new float*[rows];
for (int i = 0; i < rows; ++i)
data[i] = new float[cols];
}
// 析构函数,释放内存
~Matrix() {
for (int i = 0; i < rows; ++i)
delete[] data[i];
delete[] data;
}
// 加法运算
void add(Matrix& other) {
if (rows != other.rows || cols != other.cols)
throw std::invalid_argument("Matrices must have the same dimensions");
for (int i = 0; i < rows; ++i)
for (int j = 0; j < cols; ++j)
data[i][j] += other.data[i][j];
}
// 输出数据
void print() {
for (int i = 0; i < rows; ++i) {
for (int j = 0; j < cols; ++j)
std::cout << data[i][j] << " ";
std::cout << "\n";
}
}
};
int main() {
// 创建两个矩阵
Matrix m1(3, 3);
Matrix m2(3, 3);
// 初始化数据
for (int i = 0; i < m1.rows; ++i)
for (int j = 0; j < m1.cols; ++j)
m1.data[i][j] = static_cast<float>(i + j);
// 进行矩阵加法
m1.add(m2); // 假设 m2 的数据也已经初始化好了
// 输出结果
std::cout << "Matrix 1 after addition:\n";
m1.print();
return 0;
}
```
②. 使用`new`和`delete`操作 `student` 结构体:
```cpp
#include <iostream>
#include <string>
// 定义student结构体
struct student {
int num;
std::string name;
char sex;
};
// 动态创建student对象
student* createStudent(int num, const std::string& name, char sex) {
student* p = new student();
p->num = num;
p->name = name;
p->sex = sex;
return p;
}
// 打印student对象
void printStudent(student* s) {
std::cout << "Number: " << s->num << ", Name: " << s->name << ", Sex: " << s->sex << '\n';
}
int main() {
// 创建一个学生对象
student* stu = createStudent(1001, "Alice", 'F');
// 输出学生信息
printStudent(stu);
// 释放动态内存
delete stu;
return 0;
}
```
阅读全文