std::vectorから派生した次のクラスBがあります
class B: public std::vector <unsigned int>
{
public:
B() : std::vector <unsigned int> ( 0 ) {}
};
そして次のように書かれたクラスA:
class A
{
private:
B b;
double x;
public:
B & getB () {return b;}
B const & getB() const {return b;}
bool operator() ( const A & a ) const
{
return a < a.x;
}
};
std :: listに格納されているオブジェクトAの変数bへの参照をそのイテレータから返すことができないのはなぜですか(そしてその方法)?
int main ()
{
std::set <A > alist;
std::set <A> ::iterator i_alist = alist.begin();
for (; i_alist != alist.end(); i_list++)
{
B &il = (*i_alist).getB(); //Compiler error
B &il2 = i_alist->getB(); //Compiler error
il.push_back(10); //Modify il and concurrently B
}
}
コンパイラエラー:
Error 1 error C2440: 'initializing' : cannot convert from 'const B' to 'B &' d:\test.cpp
ご協力いただきありがとうございます...
質問の編集:
const_castを使用した可能な解決策:
B &il2 = const_cast <B&> ( i_alist->getB() );