您想要定义采用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 中的新功能。