special case of base class of Inner class
In c++, is it possible to declare inner class (CInner) such that it has outer class (COuter) as its base class ?
This quest开发者_运维问答ion is about c++ technicalities. Not question of programming style or personal preferences.
Yes. This compiles:
class COuter
{
class CInner;
};
class COuter::CInner : public COuter
{
};
The reason this is required is that a derived class requires that the entire definition be present for its own definition. So you just need to make sure that the outer class is completely defined before the inner class's definition starts.
It's possible to declare inner/nested class derived from enclosing class. but you can't define your nested class at the same time. for example, if you try to compile this code, it'll throw invalid use of incomplete type COuter.
class COuter
{
class CInnner : COuter
{
}
}
but if you just declare your class and delay definition of inner class, it'll work because then the Couter class definition will be complete. In other words, you can't use a type unless it's defined completely.
As John Calsbeek said, following line of code will work.
class COuter
{
class CInner;
};
class COuter::CInner : public COuter
{
};
This topic is also discussed here for reference. Can a nested C++ class inherit its enclosing class?.
The following code compiles and runs fine:
#include <iostream>
using namespace std;
class COuter
{
public:
COuter ()
{
cout << "COuter() called" << endl;
}
class CInner;
};
class COuter::CInner : public COuter
{
public:
CInner()
{
cout << "COuter::CInner() called" << endl;
}
};
int main()
{
COuter o;
COuter::CInner i;
return 0;
}
Output:
$ ./inner-outer.exe
COuter() called
COuter() called
COuter::CInner() called
精彩评论