// 不能被继承的类
// 【1】显然继承需要构造函数和析构函数,因此将它们定义为private可以防止继承,
// 这样的话只能在栈中实例化,典型的例子是单件模式,或者其退化版本。
#include <iostream>
using namespace std;
class S // 标准单件模式1
{
public:
static S* get_instance()
{
if(sp) return sp;
else return (sp=new S);
}
void print(){cout<<"It is S"<<endl;}
void destroy()
{
delete this;
}
private:
static S*sp;
S(){cout<<"S::ctor"<<endl;}
~S(){cout<<"S::dector"<<endl;}
};
S* S:: sp=0;
////////////////////////////////////
class NS // 单件模式退化版本
{
public:
static NS* get_instance()
{
return new NS;
}
void print(){cout<<"It is NS"<<endl;}
void destroy()
{
delete this;
}
void destroy(NS*p)
{
delete p;
p=0;
}
private:
NS(){cout<<"NS::ctor"<<endl;}
~NS(){cout<<"NS::dector"<<endl;}
};
//////////////////////////////////// 虚继承搞定! 虚继承以后,grand_child就绕过Child,直接调用Parent的构造函数,于是就出错了。
class Child;
class Parent
{
friend class Child;
private:
Parent(){cout<<"Parent::ctor"<<endl;}
~Parent(){cout<<"Parent::dector"<<endl;}
};
class Child: virtual public Parent
{
public:
Child(){cout<<"Child::ctor"<<endl;}
~Child(){cout<<"Child::dector"<<endl;}
void print(){cout<<"It is Child"<<endl;}
};
class grand_child:public Child
{
public:
// 这两句话无法通过编译,奇怪的是,如果不定义构造和析构,是可以暂时通过编译的,只是一到了实例化的时候就错了
// grand_child(){cout<<"grand_child::ctor"<<endl;}
// ~grand_child(){cout<<"grand_child::dector"<<endl;}
};
int main()
{
// grand_child gc; // 这句话无法通过编译。
cout<<sizeof(grand_child)<<endl;
return 0;
}
输出结果为4.
下面是一个漂亮的模板化的实现,当然,不是我写的。。
前天,一个同事给我看了一段代码,问我这段代码的涵义。乍一看我没有看出明堂。后来在与几个同事一起深入研究后发现了它的奥妙。这其中涉及到一些C++中的高级技术,很有意思。我把我们的分析作了一个总结,借这块宝地,拿出来供大家共同学习。原始代码如下:
|
//file name: NoInherit.h template <class T> class NoInherit_;
template <class T,template<class > class A > class NoInherit_< A<T> > { private: friend A<T>; friend T; NoInherit_(){} };
template <class T> class NoInherit:virtual public NoInherit_< NoInherit< T> > { public: typedef T type; private: friend T; NoInherit():NoInherit_< NoInherit< T> >() {} }; |
如果你是大虾一下子就看明白了这段代码,那么这篇文章对你就没有多大价值了,兄弟就不敢再耽搁你的时间了。如果你不能一下子看出来,那就让我来告诉你吧。它是一个不能被其它类继承的类模板。不信你试试……

按照下面的方法使用这个模板:
|
class CA:NoInherit<CA> { //…… }; |
这个类CA不能再被其它类继承了.像这样
|
Class CB:CA {
} //error……编译会出错。提示不能访问NoInherit_的私有构造函数。 |
348

被折叠的 条评论
为什么被折叠?



