what is containership or nesting in C++?
what i understood is: Containership: a class contains another class objects as member data.
please explain wit开发者_运维百科h an example.
Thanks.
Class nesting is simply to have a class defined in another class, like that :
class A
{
public:
class B
{
public:
class C{};
};
};
Then you can access a nested class using the scope operator, like you would do with namespaces :
A a;
A::B b;
A::B::C c;
Now when a class contain another class's object, it's an aggregation :
class D
{
public:
A myA;
void do_something();
private:
A::B myB;
};
Then you can access the member like that if it's public :
D d;
process( d.myA ); // access to myA
If it's not accessible, then you can provide it via a function. Anyway, inside the class functions, you can directly access the member :
void D::do_something()
{
doit( myB );
// or
doit( this->myB );
}
Containership simply means an object can be accessed inside another.
For instance :
class Contained
{
int foo;
};
class Container
{
Contained bar;
};
You can access foo like this :
Container c;
c.bar.foo = 42;
Class nesting is different. It means you are declaring a class from inside another :
class AngryMammoth
{
class CrazyVulture
{
int legCount;
};
int numberOfPeopleKilledSoFar;
};
class In {};
class Out {
In object;
};
Similar to inheritance, an object of class A
is embedded in the object of class B
:
class A {
int x;
};
class B {
int y;
A a1;
A a2;
};
If you would instantiate B b
, you would get something like this on your memory:
int y; // b.y
int x; // b.a1.x
int x; // b.a2.x
Contrary to a pointer attribute, a nested object actually sits inside the outer object. Also you do not have to worry about creating/deleting A
as it is automatically done when B
is created/deleted.
精彩评论