在c++中使用[]而不是函数调用

Using [] rather than a function call in c++

本文关键字:函数调用 c++      更新时间:2023-10-16

在课堂上,我们被要求写一部分代码,使老师写的东西正常工作。问题是,我不认识语法。我问了一个朋友,他说这可能是一个超载的运营商,但我只是不知道该怎么办。

    templateClass < int > obj(array, arrayS);                   
    cout << obj[1] << endl; 

所以它似乎应该输出数组obj将持有的槽1,但正如我所说的,我从未见过在没有()和参数的情况下使用这个。

是否重载了[]操作符?它如何应用于整个物体?

谢谢。

templateClass < int > obj(array, arrayS);int obj(5);的语法类型相同。

表示我们声明了一个对象obj。类型为templateClass<int>,初始化器为arrayarrayS,它们最终将作为类构造函数的参数。

obj[1]表示在obj上调用重载的operator[]。要了解它的实际作用,您需要查找templateClass的类定义。(或者如果你想让obj[1]工作,你需要在templateClass的类定义中编写一个重载的operator[])。

以下面的类

为例
template <typename T>
class SimpleArray {
public:
    SimpleArray(const T& first_in = T(), const T& second_in = T()) :
        first(first_in), second(second_in) { }
    T& get(int index) {
        return (index == 0) ? (first) : (second);
    }
private:
    T first;
    T second;
};

假设main中有

int main() {
    SimpleArray<int> simple(1,2);
    cout << simple.get(0) << ' ' << simple.get(1) << endl;
    return 0;
}

所以这只是简单地创建一个类型为'SimpleArray'的对象,T作为int(传递1和2作为其构造函数的参数)。然后,只需调用get(),在简单三元操作符的帮助下返回所请求的元素。现在可以重载[]操作符,如下所示

template <typename T>
class SimpleArray {
public:
    SimpleArray(const T& first_in = T(), const T& second_in = T()) :
        first(first_in), second(second_in) { }
    T& get(int index) {
        return (index == 0) ? (first) : (second);
    }
    T& operator[] (int index) {
        return this->get(index);
    }
private:
    T first;
    T second;
};

并在main

中进行测试
int main() {
    SimpleArray<int> simple(1,2);
    cout << simple.get(0) << ' ' << simple.get(1) << endl;
    cout << simple[0] << ' ' << simple[1] << endl;
    return 0;
}

在这里,您只需在每次使用[]语法访问数组元素时调用get()函数

我是这样看作业的:

编写一个模板类,接受以下行:

templateClass < int > obj(array, arrayS);
cout << obj[1] << endl;

第一行是带参数的构造函数,模板类型为int,第二行是[]操作符。

但是对模板的功能没有特定的要求。换句话说,只要构造函数接受两个实参(模板类型为int),并且模板类提供[]操作符,你就可以发挥你的想象力,实现任何你喜欢的东西。

看变量名(array, arrayS),似乎老师想让你传递一个数组和数组的大小。因此,templateClass的一个想法可以是这样一个类,它接受c风格的数组作为输入,并将值存储在某个c++容器中。

可以这样做:

template <typename T>
class templateClass {
public:
    // Constructor taking array T[] and size as arguments (first requirement)
    templateClass(const T d[], const size_t size)
    {
        for (int i=0; i < size; i++)
        {
            // Copy data from c-style array to a c++ vector 
            mData.push_back(d[i]);
        }
    }
    // [] operator (second requirement)
    T& operator[] (int index)
    {
        if ((index >= mData.size()) || (index < 0))
        {
            // Error - out of range
            // You could throw an exception here or some other error handling
            throw std::invalid_argument( "Invalid index" );
        }
        return mData[index];
    }
private:
    std::vector<T> mData;
};
int main()
{
    try
    {
        int arr[3] = {5, 4, 9};
        templateClass < int > obj(arr, sizeof(arr)/sizeof(arr[0]));
        cout << obj[0] << endl;
        cout << obj[1] << endl;
        cout << obj[2] << endl;
        // Invalid index - will throw exception
        cout << obj[3] << endl;
    }
    catch(...)
    {
        cout << "Exception....";
    }
    return 0;
}