简体   繁体   English

我究竟如何重载“{”运算符?

[英]How exactly can I overload the '{' operator?

To initialize an std::vector, I can directly use the initializer_list, like so:要初始化 std::vector,我可以直接使用 initializer_list,如下所示:

std::vector<int> myVec = {1, 2, 3, 4};

If i create a custom List Class (which will hold a number of items), for example class customVector (for simplicity only with ints, I think I could figure out how to do it with templates myself, if necessary), can I overload the operator '{' in such a way that an instance of customVector can be initialized in the same matter?如果我创建一个自定义列表类(它将包含许多项目),例如class customVector (为了简单起见,仅使用整数,我想我可以自己弄清楚如何使用模板,如果需要的话),我可以重载运算符 '{' 以这样一种方式可以在同一件事中初始化customVector的实例吗? So that I could write这样我就可以写

customVector myCustomVec = {1, 2, 3, 4}

You can accomplish what you ultimately want, but not by overloading any operators – { is not an operator.你可以完成你最终想要的,但不能通过重载任何运算符—— {不是运算符。

vector does this by having a constructor that takes an initializer_list parameter, and you can do the same with your class. vector通过使用一个带initializer_list参数的构造函数来做到这一点,你可以对你的类做同样的事情。

Learning how to do it and implementing it left as an exercise.学习如何做并实施它作为练习。

You cannot, since { is not an operator.您不能,因为{不是运算符。 Up to C++20 , the following operators were overridable:C++20 ,以下运算符是可覆盖的:

+    -    *    /    %    ^    &    |    ~    !    =
<    >    +=   -=   *=   /=   %=   ^=   &=   |=   <<
>>   >>=  <<=  ==   !=   <=   >=   &&   ||   ++   --
,    ->*  ->   ()   []

C++20 added the spaceship operator <=> but I believe that's it. C++20添加了飞船操作符<=>但我相信就是这样。

As the others have pointed at, { is not an operator.正如其他人指出的那样, {不是运算符。 However, you can still use the initializer list as you like.但是,您仍然可以根据需要使用初始化列表 It's a part of the standard library.它是标准库的一部分。

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

template <typename T>
struct customVector {
    customVector(std::initializer_list<T> list) : size(list.size()) {
        arr = new T[size];
        int count = 0;
        for(auto val: list) arr[count++] = val;
    }
    T* arr;
    std::size_t size;

    ~customVector() {
        for(int i = 0; i < size; i++)
            std::cout << arr[i] << std::endl;
        delete [] arr;
    }
};

int main() {
    customVector<int> myCustomVec = {1, 2, 3, 4};
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM