-
November 27th, 2009, 08:01 AM
#1
const iterator
Hi,
I have a problem with a constant iterator. This is an example of the situation
class B
{
public:
B(){}
std::list<int> m_List;
std::list<int>::iterator Iter;
const int Func ( ) const
{
std::list<int>::iterator IterFunc;
IterFunc = m_List.begin ( );
return 2;
}
};
int main ( )
{
B ObjB;
ObjB.Func ( );
return 0;
}
I have this compilation error
error C2679: binary '=' : no operator found which takes a right-hand operand of type 'std::list<_Ty>::_Const_iterator<_Secure_validation>' (or there is no acceptable conversion)
If I remove the const at the end of Func it solves the problem but I need this function to be const. How I can solve this problem
Thank you
-
November 27th, 2009, 08:08 AM
#2
Re: const iterator
Code:
const int Func ( ) const
{
std::list<int>::const_iterator IterFunc;
IterFunc = m_List.begin ( );
return 2;
}
-
November 27th, 2009, 08:11 AM
#3
Re: const iterator
Perfect, Thank you for your answer
-
November 27th, 2009, 08:13 AM
#4
Re: const iterator
Originally Posted by Geof
Hi,
I have a problem with a constant iterator. This is an example of the situation
class B
{
public:
B(){}
std::list<int> m_List;
std::list<int>::iterator Iter;
const int Func ( ) const
{
std::list<int>::iterator IterFunc;
IterFunc = m_List.begin ( );
return 2;
}
};
int main ( )
{
B ObjB;
ObjB.Func ( );
return 0;
}
I have this compilation error
error C2679: binary '=' : no operator found which takes a right-hand operand of type 'std::list<_Ty>::_Const_iterator<_Secure_validation>' (or there is no acceptable conversion)
If I remove the const at the end of Func it solves the problem but I need this function to be const. How I can solve this problem
Thank you
Func is const, that means inside Func, all member variables are const, including m_list. When you call begin on m_list, you are calling the const version of begin, which returns a const iterator.
You cannot assign a const_iterator to an iterator, because that would break const correctness,
If you are not planning to use iterfunc to modify you list, then declare it const_iterator. If you ARE planning to use it to modify your list, then don't call Func const, since it isn't.
You should know that constness IS part of function signatures. Writing: could call two different functions depending on your list constness:
Code:
iterator begin(); //non const version, returning a non const iterator
const_iterator begin() const; //const version returning a const_iterator
Your compiler will always try to use non-const functions if your object is not const, and const functions if your object is const.
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
-
Forum Rules
|
Click Here to Expand Forum to Full Width
|