0

我在对变量进行 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]

如果您能帮我解决问题,我将不胜感激。谢谢

4

2 回答 2

4

你需要一个函数的const重载get(),你可以在一个const对象上调用它;它必须返回一个const引用,因为它只能调用以下的const重载employee_set::get()

class A
{
private:
    employee_set m_employees;
public:
    first_name_view& get()
    {
        return m_employees.get<0>();
    }
    first_name_view const & get() const   //< Add this
    {
        return m_employees.get<0>();
    }
};

然后你需要用它来初始化一个const引用:

first_name_view const & fdv = a1->get();
             // ^^^^^ add this
于 2012-05-11T05:18:52.567 回答
3

a1是一个常量指针,但该方法A:get()可能会修改对象的内容,因为该方法未标记为const.

在参数列表之后添加一个 const 限定符:

first_name_view& get() const
{
    return m_employees.get<0>();
}
于 2012-05-11T04:57:44.033 回答