动态数组类

在动态数组类中,通过类的成员函数访问数组元素,可以在每次访问之前检查一下下标是否越界,使得数组下标越界的错误能够及早被发现。这种检查,可以通过C++的assert来进行。assert的含义是“断言”,它是标准C++的cassert头文件中定义的一个宏,用来判断一个条件表达式的值是否为true,如果不为true,则程序会中止,并且报告出错误,这样就很容易将错误定位。
以下是一个简单的动态数组类示例

 #include<iostream>
 #include<cassert>
using namespace std;
class point{
public:
    point():x(0),y(0)
    {
        cout<<"default constructor called."<<endl;
    }
    point(int x,int y):x(x),y(y)
    {
        cout<<"constructor called."<<endl;
    }
    ~point()
    {
        cout<<"destructor called."<<endl;
    }
    int getx() const {return x;}
    int gety() const {return y;}
    void movee(int newx,int newy)
    {
        x=newx;
        y=newy;
    }
private:
    int x,y;

};
class arrayofpoints
{
public:
    arrayofpoints(int sizee):sizee(sizee)
    {
           points=new point[sizee];
    }
    ~arrayofpoints()
    {
        cout<<"deleting..."<<endl;
        delete[] points;
    }
    //获得下标为index的数组元素
    point element(int index)
    {
        assert(index>=0&&index<sizee);//如果数组下标越界,程序中止
        return points[index];
    }
private:
    point *points;
    int sizee;
};
int main()
{
    int countt;
    cout<<"please enter the count of points:";
    cin>>countt;
    arrayofpoints points(countt);//创建对象数组
    points.element(0).movee(5,0);//访问数组元素的成员
    points.element(1).movee(15,20);
    return 0;
}

个人理解:简单来说就是通过类的组合,实现 一个类point是另一个数组类arrayofpoints的元素,如果理解不到位,欢迎改正。

  • 3
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值