boost :: assign用于不能使用+ =的集合

时间:2014-03-18 13:24:37

标签: c++ boost

我正在尝试使用Boost :: assign和operator + =来初始化我计划稍后使用的静态集。我按照此link中指定的步骤操作。代码分为三个文件

/*Assign.hpp*/
#ifndef __SAMPLE_CLASS__
#define __SAMPLE_CLASS__

#include <iostream>
#include <set>
#include <string>
#include <boost/assign/std/set.hpp>

class SampleClass
{
    public:
        SampleClass();
        ~SampleClass();

        typedef std::set<int> SET_TYPE;

        static const SET_TYPE my_set1;
        static const SET_TYPE my_set2;
};

#endif

/*Assign.cpp*/
#include "assign.hpp"

using namespace boost::assign;

const SampleClass::SET_TYPE SampleClass::my_set1 += 1,2,3;
const SampleClass::SET_TYPE SampleClass::my_set2 += 4,5,6;

SampleClass::SampleClass()
{

}

SampleClass::~SampleClass()
{

}

/*main.cpp*/
#include "assign.hpp"                    

int main()
{
    SampleClass sobj;
    return 0;
}

发出以下命令时出现以下编译错误

g++ -I /usr/local/include main.cpp assign.cpp

错误代码段

assign.cpp:6:50: error: invalid '+=' at end of declaration; did you mean '='?
const SampleClass::SET_TYPE SampleClass::my_set1 += 1,2,3;
                                             ^~
                                             =
assign.cpp:6:42: error: no viable conversion from 'int' to 'const SampleClass::SET_TYPE' (aka 'const set<int>')
const SampleClass::SET_TYPE SampleClass::my_set1 += 1,2,3;
                                     ^          ~
assign.cpp:6:55: error: expected unqualified-id
const SampleClass::SET_TYPE SampleClass::my_set1 += 1,2,3;
                                                  ^
assign.cpp:6:55: error: expected ';' after top level declarator
const SampleClass::SET_TYPE SampleClass::my_set1 += 1,2,3;

...

我尝试初始化静态集或使用+ =运算符的方式是否有问题?

2 个答案:

答案 0 :(得分:2)

您不能在初始化语句中使用+=

答案 1 :(得分:0)

如果你的编译器支持c ++ 11,你可以像这样改变它:

const SampleClass::SET_TYPE SampleClass::my_set1 = {1,2,3};
const SampleClass::SET_TYPE SampleClass::my_set2 = {4,5,6};