首页 > 其他 > 详细

空类的默认函数—— SAP电面(2)/FEI

时间:2015-06-11 16:22:56      阅读:209      评论:0      收藏:0      [点我收藏+]

定义一个空类

class Empty
{
};

默认会生成以下几个函数

2. 拷贝构造函数

Empty(const Empty& copy)
{
}

3. 赋值运算符

Empty& operator = (const Empty& copy)
{
}

4. 析构函数(非虚)

~Empty()
{
}

这些函数只有在第一次使用它们的时候才会生成,他们都是inline并且public的。如果想禁止生成这些函数,可以将它们定义成private函数,如果有很多类都有这种需求,那么可以定义一个基类,然后让其他类继承这个类。下面是来自boost库的代码,任何继承了该类的类,都不能进行复制操作。也不能使用赋值运算符。

 1 #ifndef BOOST_NONCOPYABLE_HPP_INCLUDED
 2 #define BOOST_NONCOPYABLE_HPP_INCLUDED
 3 
 4 namespace boost {
 5     //  Private copy constructor and copy assignment ensure classes derived from
 6     //  class noncopyable cannot be copied.
 7     //  Contributed by Dave Abrahams
 8     namespace noncopyable_  // protection from unintended ADL
 9     {
10         class noncopyable
11         {
12         protected:
13             noncopyable() {}
14             ~noncopyable() {}
15         private:  // emphasize the following members are private
16             noncopyable( const noncopyable& );
17             const noncopyable& operator=( const noncopyable& );
18         };
19     }
20 
21     typedef noncopyable_::noncopyable noncopyable;
22 
23 } // namespace boost
24 
25 #endif  // BOOST_NONCOPYABLE_HPP_INCLUDED

 

转载:http://www.cnblogs.com/graphics/archive/2010/07/14/1776950.html

空类的默认函数—— SAP电面(2)/FEI

原文:http://www.cnblogs.com/alanhu/p/4569065.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!