我在对变量进行 const 操作时遇到问题。我已将问题简化为以下程序:
#include <string>
#include <iostream>
#include <boost/multi_index_container.hpp>
#include <boost/multi_index/member.hpp>
#include <boost/multi_index/ordered_index.hpp>
#include <boost/multi_index/sequenced_index.hpp>
using boost::multi_index::multi_index_container;
using boost::multi_index::ordered_non_unique;
using boost::multi_index::ordered_unique;
using boost::multi_index::indexed_by;
using boost::multi_index::member;
using boost::multi_index::sequenced;
struct employee_entry
{
employee_entry( const std::string& first,
const std::string& last,
long id):
first_name_(first),
last_name_(last),
id_(id)
{}
std::string first_name_;
std::string last_name_;
long id_;
};
typedef multi_index_container<
employee_entry, indexed_by<
ordered_unique<member<employee_entry, std::string , &employee_entry::first_name_> >
, ordered_non_unique<member<employee_entry, std::string , &employee_entry::last_name_> >
, ordered_non_unique<member<employee_entry, long , &employee_entry::id_> >
,sequenced<>
>
> employee_set;
using boost::multi_index::nth_index;
using boost::multi_index::get;
typedef nth_index<employee_set, 0>::type first_name_view;
class A
{
private:
employee_set m_employees;
public:
first_name_view& get()
{
return m_employees.get<0>();
}
};
int main()
{
A *a = new A;
first_name_view& fnv = a->get();
fnv.insert(employee_entry("John", "Smith", 110));
fnv.insert(employee_entry("John1", "Hunk", 97));
const A *a1 = a;
first_name_view& fdv = a1->get();
for(first_name_view::iterator it = fdv.begin(), it_end(fdv.end()); it != it_end; ++it)
{
//....
}
return 0;
}
假设变量a1 必须是常量,我得到编译错误:
$ c++ dr2.cpp
dr2.cpp: In function ‘int main()’:
dr2.cpp:66:35: error: passing ‘const A’ as ‘this’ argument of ‘first_name_view& A::get()’ discards qualifiers [-fpermissive]
如果您能帮我解决问题,我将不胜感激。谢谢