为什么c++没有虚构造函数?
当前回答
“构造函数不能是虚拟的”
有一些合理的理由可以证明这种说法是正确的。
要创建对象,对象类的构造函数必须与类的类型相同。但是,对于虚拟实现的构造函数,这是不可能的。 在调用构造函数时,还没有创建虚表来解析任何虚函数调用。因此,虚拟构造函数本身将没有任何可以查找的地方。
因此,不可能将构造函数声明为虚函数。
其他回答
The virtual mechanism only works when you have a based class pointer to a derived class object. Construction has it's own rules for the calling of base class constructors, basically base class to derived. How could a virtual constructor be useful or called? I don't know what other languages do, but I can't see how a virtual constructor could be useful or even implemented. Construction needs to have taken place for the virtual mechanism to make any sense and construction also needs to have taken place for the vtable structures to have been created which provides the mechanics of the polymorphic behaviour.
我能想到两个原因:
技术原因
对象只有在构造函数结束后才存在。为了使用虚拟表分派构造函数,必须有一个现有的对象和指向虚拟表的指针,但是如果对象仍然不存在,指向虚拟表的指针怎么可能存在呢?:)
逻辑的原因
当您想要声明某种多态行为时,可以使用virtual关键字。但是构造函数没有任何多态性,c++中的构造函数只是简单地将对象数据放到内存中。由于虚表(以及一般的多态性)都是关于多态行为而不是多态数据的,因此声明虚构造函数没有任何意义。
If you think logically about how constructors work and what the meaning/usage of a virtual function is in C++ then you will realise that a virtual constructor would be meaningless in C++. Declaring something virtual in C++ means that it can be overridden by a sub-class of the current class, however the constructor is called when the objected is created, at that time you cannot be creating a sub-class of the class, you must be creating the class so there would never be any need to declare a constructor virtual.
另一个原因是,构造函数的名字与其类名相同如果我们将构造函数声明为virtual,那么它应该在它的派生类中以相同的名字重新定义,但两个类的名字不能相同。所以不可能有一个虚拟构造函数。
虚函数基本上提供多态行为。也就是说,当您使用的对象的动态类型与引用它的静态(编译时)类型不同时,它提供的行为适合于对象的实际类型,而不是对象的静态类型。
现在尝试将这种行为应用于构造函数。当你构造一个对象时,静态类型总是与实际的对象类型相同,因为:
要构造一个对象,构造函数需要它要创建的对象的确切类型[…]此外[…]]则不能有指向构造函数的指针
Bjarne Stroustup (P424 c++编程语言SE)
我们不能简单地说…我们不能继承构造函数。因此没有必要将它们声明为虚拟的,因为虚拟提供了多态性。
推荐文章
- 如何构建和使用谷歌TensorFlow c++ api
- 实例属性attribute_name定义在__init__之外
- 断言是邪恶的吗?
- 下面这些短语在c++中是什么意思:0 -,default-和value-initialization?
- 在STL地图中,使用map::insert比[]更好吗?
- C++ Linux的想法?
- 如何为Fedora安装g++ ?
- Std::cin输入空格?
- c++标准是否要求iostreams的性能很差,或者我只是在处理一个糟糕的实现?
- gcc在哪里查找C和c++头文件?
- 为什么我们需要require require ?
- 具有构造签名的接口如何工作?
- 解析c++中的命令行参数?
- 我如何在c++中创建一个随机的字母数字字符串?
- c++中的atan和atan2有什么区别?