设计一个学生类(Student),包括私有数据成员:学号(int型),姓名,成绩(int型),函数成员根据需要定义。 设计一个数组类模板(Array),形式大致如下: class Array{ private: int size; T *element; public: ~Array();//析构函数 operator>>//重载输入运算符 operator<<//重载输出运算符 void sort();//对数组内数据排序 };
时间: 2024-03-12 20:49:26 浏览: 24
下面是学生类(Student)的定义:
```cpp
class Student {
private:
int id; // 学号
string name; // 姓名
int score; // 成绩
public:
Student(int _id, string _name, int _score) : id(_id), name(_name), score(_score) {}
int getId() const { return id; }
string getName() const { return name; }
int getScore() const { return score; }
void setId(int _id) { id = _id; }
void setName(string _name) { name = _name; }
void setScore(int _score) { score = _score; }
};
```
下面是数组类模板(Array)的定义:
```cpp
template <typename T>
class Array {
private:
int size; // 数组大小
T* element; // 数组元素
public:
Array(int _size) : size(_size), element(new T[size]) {}
~Array() { delete[] element; }
friend istream& operator>>(istream& in, Array<T>& arr) {
for (int i = 0; i < arr.size; i++)
in >> arr.element[i];
return in;
}
friend ostream& operator<<(ostream& out, const Array<T>& arr) {
for (int i = 0; i < arr.size; i++)
out << arr.element[i] << " ";
return out;
}
void sort() {
for (int i = 0; i < size - 1; i++) {
for (int j = 0; j < size - i - 1; j++) {
if (element[j] > element[j + 1]) {
T temp = element[j];
element[j] = element[j + 1];
element[j + 1] = temp;
}
}
}
}
};
```
在上述代码中,构造函数中通过new关键字动态分配内存来初始化数组元素,析构函数中释放分配的内存。重载输入和输出运算符分别用于输入和输出数组元素。sort()函数通过冒泡排序对数组元素进行排序。由于sort()函数不需要访问类的私有成员,因此没有将其声明为类的成员函数。此外,为了让sort()函数适用于不同类型的数组,将数组类模板(Array)声明为一个模板类。