ICode9

精准搜索请尝试: 精确搜索
首页 > 编程语言> 文章详细

C++函数调用操作符重载()

2021-11-17 12:30:37  阅读:149  来源: 互联网

标签:const int C++ operator len1 函数调用 数组 重载 Array


#include <iostream>
#include <string>
using namespace std;

class Array
{
public:
    Array(){ len1=0; len2=0;num=NULL;};
    Array(int m,int n);

    int &operator ()(int ,int );
    const int &operator ()(int ,int ) const;

    int getlen1()const {return len1;}
    int getlen2()const {return len2;}

private:
    int len1;
    int len2;
    int *num;

};


Array::Array(int m, int n) {
    int size=m*n;
    try{
        num= new int [size];
    }
    catch (bad_alloc)
    {
        cerr<<"allocate storage failure !"<<endl;
        throw;
    }
    len1=m;
    len2=n;
}

int & Array::operator()(int i, int j) {
    if (i < 0 || i >= len1)
        throw string("数组行溢出");
    if (j < 0 || j > len2)
        throw string("数组列溢出");

    return num[i*len1+j];
}

const int & Array::operator()(int i, int j) const {
    if (i < 0 || i >= len1)
        throw string("数组行溢出");
    if (j < 0 || j > len2)
        throw string("数组列溢出");

    return num[i*len1+j];
}

int main(){

    Array A(3,4);
    int i,j;

    for (i=0;i<A.getlen1();i++)
       for (j=0;j<A.getlen2();j++)
           A(i,j)=i*A.getlen2()+j;
    for (i=0;i<A.getlen1();i++)
        for (j=0;j<A.getlen2();j++)
            cout<<A(i,j)<<" ";
    cout<<endl;
    try
    {
        cout<< A(5, 3) << endl;
    }
    catch(string s)
    {
        cerr<<s<<endl;
    }

    try
    {
        cout<< A(5, 3) << endl;
    }
    catch(string s)
    {
        cerr<<s<<endl;
    }
    return 0;

}


在这个例子中,我们定义了一个 Array 类,这个类描述的是一个二维数组。在类中,我们先定义了一个默认构造函数,之后声明了一个带参数的构造函数Array(int m, int n);,两个参数分别表示数组的两个维度值。之后声明了两个函数调用操作符重载函数,分别是:

int & operator()(int, int);
const int & operator()(int, int)const;

因为只有常成员函数才能处理常对象

所以我们依然在类中提供两个版本的函数调用操作符重载函数。我们可以看一下这两个函数的函数定义,在它们的函数体中,我们先是做一个越界检测,当然对于二维数组而言,边界是有两个的,因此有两次边界检测,如果没有越界,则会返回对应的值。

有了这两个函数调用操作符重载函数,我们就可以用 A(i,j) 的形式访问二维数组中的数据了。当我们用 A(i,j) 的形式访问二维数组中的数据时,A(i,j) 会调用类中的函数调用操作符重载函数,此时 A(i,j) 可以理解为:

A.operator()(i, j)

标签:const,int,C++,operator,len1,函数调用,数组,重载,Array
来源: https://blog.csdn.net/luoganttcc/article/details/121375316

本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享;
2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关;
3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关;
4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除;
5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。

专注分享技术,共同学习,共同进步。侵权联系[81616952@qq.com]

Copyright (C)ICode9.com, All Rights Reserved.

ICode9版权所有