1

私には本当に簡単な方法があります:

void SomeClass::GetListStuff(std::vector<Stuff const *> &listStuff) const
{   listStuff = m_listStuff;   }

ここで、m_listStuffはSomeClassのメンバーであり、タイプは

std::vector<Stuff *> 

このコードは私に次のようなエラーを出します

there's no match for 'operator='
in 'listStuff = ((const SomeClass*)this)->SomeClass::m_listStuff

ListStuffポインターからconstを削除すると、正常に機能します。(constの正当性を変更せずに)listStuffでinsert()を呼び出すこともでき、それは機能します。誰かが理由を説明できますか?

4

1 に答える 1

1

私はあなたがこれをすべきだと思います:

void SomeClass::GetListStuff(std::vector<Stuff*> &listStuff) const
{   
       listStuff = m_listStuff;   
}

つまり、が宣言されていると思われるため、std::vector<Stuff*>の代わりに使用します。したがって、引数の型はそれに一致する必要があります。std::vector<Stuff const*>m_listStuffstd::vector<Stuff*>

より良いアプローチはこれだと思います:

std::vector<Stuff*> SomeClass::GetListStuff() const
{   
       return m_listStuff; //return a copy!
}

または、イテレータを公開することをお勧めします。

std::vector<Stuff*>::const_iterator cbegin() const
{   
       return m_listStuff.cbegin(); //return const_iterator (C++11 only)
                                    //in C++03, you can use begin()
                                    //it will work same as cbegin()
}
std::vector<Stuff*>::const_iterator cend() const
{   
       return m_listStuff.cend(); //return const_iterator (C++11 only)       
                                  //in C++03, you can use end()
                                    //it will work same as cend()
}

非定数バージョンを自分で作成します。

于 2013-01-05T05:21:47.137 に答える