1

我应该重载哪个运算符来捕获列表分配

whatever myints[] = {32,71,12,45,26,80,53,33};

如果你有一些例子会很好吗?如果我要重载赋值,我收到的参数类型是什么?

编辑:哦,所以它是构造函数,列表是什么类型?

Edit2:所以它应该是这样的(来自http://en.cppreference.com/w/cpp/utility/initializer_list

S(std::initializer_list<T> l) : v(l) {
 std::cout << "constructed with a " << l.size() << "-element list\n";
}

正确的?

4

1 回答 1

2

您想要定义采用std::initialize_list<int>. 例如:

MadeFromList.h

#ifndef _MADE_FROM_LIST_H_
#define _MADE_FROM_LIST_H_

#include <vector>
#include <ostream>
#include <initializer_list>

class MadeFromList {
public:
    MadeFromList(const std::initializer_list<int>& integers) :
        myVector(integers)
    {}
private:
    std::vector<int> myVector;

    friend std::ostream& operator<<(std::ostream&, const MadeFromList&);
};

std::ostream& operator<<(std::ostream& outputStream,
                         const MadeFromList& mfl)
{
    for (int x : mfl.myVector)
    {
        outputStream << x << " ";
    }
    return outputStream;
}
#endif

主文件

#include "MadeFromList.h"
#include <iostream>

int main()
{
    MadeFromList myListObject = {32, 71, 12, 45, 26, 80, 53, 33};
    std::cout << myListObject << std::endl;
    return 0;
}

编译和运行这个:

g++ -std=c++0x -W -Wall -Wextra -pedantic -o test main.cpp 
./test

给出输出:

32 71 12 45 26 80 53 33 

智者的话:此功能是 C++11 中的新功能。

于 2013-04-20T16:54:00.487 回答