DECLARATION: This question is ALL about the error IN THE PRESENCE of the following demonstrated using statement. I understand there're other similar questions on SO but none of them answered my specific question. And I know how to make it work WITHOUT the using statement.
In my header file:
class MyClass
{
public:
class MyIterator
{
public:
MyIterator& operator++(int);
private:
static const MyIterator END;
};
...
};
In my implementation file (.cc file):
using ::MyClass; //**QUESTION: I've already used the class, why did the nested MyIterator class not get recognized?** EDIT: excuse my English, I can't write - by I've already used, I mean, I've already told the compiler "using that class"
// the following line is the definition of the static const object
const MyIterator MyIterator::END = MyIterator(); //error: ‘MyIterator’ does not name a type
MyIterator& MyIterator::operator++(int) //error: ‘MyIterator’ does not name a type
{
...
}
As I put in the comment - QUESTION: I've already used the class, why did the nested 'MyIterator'class not get recognized? --- correction: I've already told the compiler "using the class", why did ...
Thanks a lot.
EDIT: Thanks a lot for pointing out the const discrepency; it was a mistake during copy paste; it has been corrected.
Note that the intention of introducing the using statement is to get rid of the fully qualified name when implementing the member function(operator overload in this case). Therefore please refrain from suggesting that.
using ::MyClass
has no effect here. A using declaration in namespace / block scope introduces a member from another namespace into the current one, avoiding the namespace qualifier. But in your case both namespaces are the same : the global one
A classic usage of such a declaration is :
#include <iostream>
#include <string>
using std::string;
int main()
{
string str = "Example";
using std::cout;
cout << str;
}
In your situation, you can use a typedef :
typedef MyClass::MyIterator MyIterator;
Or in C++11, you can use a namespace alias :
using MyIterator = MyClass::MyIterator
You could possibly use the complete qualified name for your definition (and remove the using
) :
MyClass::MyIterator& MyClass::MyIterator::operator++(int)
{
// ...
}
I find it clearer since when the reader sees it, it knows that MyIterator
is a nested type of MyClass
, no need to read and browse the using declarations.
Note:
operator++
is const, but your declaration is not : that's an error.