#include <iostream>#include <cassert>#include <cstddef>class IntArray{private: int* m_array{}; int m_length{};public: IntArray(int length) // 构造函数 { assert(length > 0); m_array = new int[static_cast<std::size_t>(length)]{}; m_length = length; } ~IntArray() // 析构函数 { // 删除之前分配的数组 delete[] m_array; } void setValue(int index, int value) { m_array[index] = value; } int getValue(int index) { return m_array[index]; } int getLength() { return m_length; }};int main(){ IntArray ar ( 10 ); // 分配 10 个整型 for (int count{ 0 }; count < ar.getLength(); ++count) ar.setValue(count, count+1); std::cout << "The value of element 5 is: " << ar.getValue(5) << '\n'; return 0;} // ar 在此处被销毁,所以析构函数 ~IntArray() 会在此时被调用
"小贴士"
如果你在编译上面程序时产生如下报错:
error: 'class IntArray' has pointer data members [-Werror=effc++]|
error: but does not override 'IntArray(const IntArray&)' [-Werror=effc++]|
error: or 'operator=(const IntArray&)' [-Werror=effc++]|