The example of this article shows that C + + implementation can not be inherited classes of methods, for C + + beginners have a certain learning value. The implementation methods are as follows:
Method One:
#include <iostream>
using namespace std;
Class A
{public
:
static * getinstance ();
static void Deleteinstance (A * PA);
Private:
A () {cout << "construct a\n";}
~a () {cout << "destruct a\n";}
};
* A::getinstance ()
{return
new A;
}
void A::d eleteinstance (A * pa)
{
delete pA;
PA = nullptr;
}
int main ()
{a
* PA = A::getinstance ();
A::d eleteinstance (PA);
Cin.get ();
}
The method is actually to take the constructor, the destructor private, so that when you want to derive a class, the derived class cannot construct a parent class, so it is not.
Method Two:
#include <iostream>
using namespace std;
Template <typename t>
class A
{
friend T;
Private:
A (int data): m_data (data) {cout << "construct A. Data:" << m_data << Endl;}
~a () {}
int m_data;
};
Class B:virtual public a<b>
{public
:
B (int data): A (data) {cout << "construct b\n";}
~b () {}
};
int main (void)
{
b b (4);
Cin.get ();
}
Class B is set as a friend of Class A so that Class B can construct a parent class as a subclass of a. At this point class B can be used normally, but you can't derive a subclass from class B because B virtual inherits a, and if you want class C:pulic B, because it's virtual inheritance, then the constructor in class C has to call the constructor of Class A directly, but B is a friend of a, C is not, So the constructor of a cannot be called directly, and a compilation error occurs. Here Class C must directly call the constructor of a.
But if you change the declaration of class B to class B:public a<b>, then you can derive a subclass C from class B, because without virtual inheritance, the constructor of Class B calls the constructor of Class A, Class B's constructor calls the Class A (b is a friend, Even if A's constructor is private, it's OK. This is a layer-by-layer call up.
I believe that through the example of this article can help you better understand the principles of C + + class and use.