我应该重载哪个运算符来捕获列表赋值
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";
}
正确?
答案 0 :(得分:2)
您想要定义采用std::initialize_list<int>
的构造函数。例如:
#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
Word to the wise:此功能是C ++ 11中的新功能。