企业🤖AI智能体构建引擎,智能编排和调试,一键部署,支持私有化部署方案 广告
重载了运算符"=","[]",">>","<<"。 构造函数中sz被赋初值0,缺省长度为0。为了能像高级程序语言中的数组一样获取给定下标I的值,重载了运算符[],还增加检查数组 是否越界的功能,c++中不做数组越界检查。重载"="的函数中,防止了无意义的自我赋值,赋值前动态空间释放并且重新分配,就达 到了整体赋值的目的。 断言函数assert是c++提供的一种功能,若断言语句的条件满足则继续执行后面的语句,否则出错处理,终止程序运行。 实现代码: ~~~ #include "iostream" #include "cstdio" #include "cstring" #include "algorithm" #include "assert.h" using namespace std; template <class T> class Array1D { public: Array1D(int sz = 0); // 缺省时长度为0 ~Array1D() { delete []elements; } T &operator [](int i) const; // 取元素值 Array1D<T> &operator = (const Array1D<T> &r); // 整体赋值 friend istream &operator>>(istream &in, Array1D<T> &r) { cout << "Input Array" << endl; for(int i = 0; i < r.size; ++i) in >> r.elements[i]; return in; } friend ostream &operator<<(ostream &out, const Array1D<T> &r) { out << "Array = " ; for(int i = 0; i < r.size; ++i) out << r.elements[i] << " "; out << endl; return out; } /* data */ private: int size; T *elements; // 指向T类型数组的指针 }; template <class T> Array1D<T>::Array1D(int sz) { assert(sz >= 0); // 越界检查,满足括号内条件才执行后面的语句 size = sz; elements = new T[sz]; } template <class T> T &Array1D<T>::operator [](int i) const { assert(i >= 0 && i < size); // 越界检查,满足括号内条件才执行后面的语句 return elements[i]; } template <class T> Array1D<T>& Array1D<T>::operator=(const Array1D<T> &r) // 数组r整体赋值给this { if(this != &r) { // 防止自我赋值 size = r.size; delete []elements; // 释放原空间 elements = new T[size]; // 重新分配空间 for(int i = 0; i < size; ++i) // 复制元素 elements[i] = r.elements[i]; } return *this; } int main(int argc, char const *argv[]) { Array1D<int> a(5), b(8); Array1D<int> c; // 采用缺省长度0 cin >> a; cout << "a " << a; cin >> b; cout << "b " << b; cout << "c " << c; cout << "a[0] = " << a[0] << endl; cout << "b[5] = " << b[5] << endl; c = b; cout << "c = b, c " << c; b = a; cout << "b = a, b " << b; return 0; } ~~~