没有子类的C对象?

我想知道是否有办法在c中声明一个对象以防止它被子类化.是否有相当于在 Java中声明最终对象?

解决方法

C++ FAQ,section on inheritance

This is known as making the class
“final” or “a leaf.” There are three
ways to do it: an easy technical
approach,an even easier non-technical
approach,and a slightly trickier
technical approach.

The (easy) technical approach is to
make the class’s constructors private
and to use the 07001
to create the objects. No one can
create objects of a derived class
since the base class’s constructor
will be inaccessible. The “named
constructors” themselves could 07002 or they could 07003.

The (even easier) non-technical
approach
is to put a big fat ugly
comment next to the class definition.
The comment could say,for example,//
We'll fire you if you inherit from
this class
or even just /*final*/
class Whatever {...};
. Some
programmers balk at this because it is
enforced by people rather than by
technology,but don’t knock it on face
value: it is quite effective in
practice.

A slightly trickier technical approach
is to exploit 07004.
Since 07005,the following
guarantees that no concrete class can
inherit from class Fred:

class Fred;

 class FredBase {
 private:
   friend class Fred;
   FredBase() { }
 };

 class Fred : private virtual FredBase {
 public:
   ...
 };

Class Fred can access FredBase‘s ctor,
since Fred is a friend of FredBase,
but no class derived from Fred can
access FredBase’s ctor,and therefore
no one can create a concrete class
derived from Fred.

If you are in extremely
space-constrained environments (such
as an embedded system or a handheld
with limited memory,etc.),you should
be aware that the above technique
might add a word of memory to
sizeof(Fred). That’s because most compilers implement virtual inheritance by adding a pointer in objects of the derived class. This is compiler specific; your mileage may vary.

相关文章

/** C+⬑ * 默认成员函数 原来C++类中,有6个默认成员函数: 构造函数 析构函数 拷贝...
#pragma once // 1. 设计一个不能被拷贝的类/* 解析:拷贝只会放生在两个场景中:拷贝构造函数以及赋值运...
C类型转换 C语言:显式和隐式类型转换 隐式类型转化:编译器在编译阶段自动进行,能转就转,不能转就编译...
//异常的概念/*抛出异常后必须要捕获,否则终止程序(到最外层后会交给main管理,main的行为就是终止) try...
#pragma once /*Smart pointer 智能指针;灵巧指针 智能指针三大件//1.RAII//2.像指针一样使用//3.拷贝问...
目录<future>future模板类成员函数:promise类promise的使用例程:packaged_task模板类例程...