简体   繁体   English

如何使编译器在C ++中创建默认构造函数?

[英]How can I make the compiler create the default constructors in C++?

Is there a way to make the compiler create the default constructors even if I provide an explicit constructor of my own? 即使我提供自己的显式构造函数,也可以使编译器创建默认构造函数吗?

Sometimes I find them very useful, and find it a waste of time to write eg the copy constructor, especially for large classes. 有时候我发现它们非常有用,并且发现浪费时间来编写例如拷贝构造函数,尤其是对于大型类。

You can't - the compiler turns off some of its auto-generated default constructor when you provide your own, so you can prevent default-constructing certain classes that way. 您不能-当您提供自己的编译器时,编译器会关闭其一些自动生成的默认构造函数,因此可以防止通过这种方式默认构造某些类。 However, I think C++0x will allow you to explicitly state a default compiler implementation, eg: 但是,我认为C ++ 0x将允许您明确声明默认的编译器实现,例如:

MyClass() = default;  // 'delete' also allowed by upcoming standard to disable

I don't think any compilers support this yet - C++0x (as the next standard has been known) is not yet final, so you'll just have to make do typing out your default constructors for now. 我认为还没有编译器支持此功能-C ++ 0x(已经知道下一个标准)尚未最终确定,因此您现在只需要输入默认的构造函数即可。 It's not much code! 代码不多! MyClass() {} will do as long as all the members are themselves default constructible. 只要所有成员本身都是默认可构造的, MyClass() {}就会MyClass() {}

The copy constructor is provided whether you define any other constructors or not. 无论是否定义其他构造函数,都将提供复制构造函数。 As long as you don't declare a copy constructor, you get one. 只要不声明副本构造函数,就可以得到一个。

The no-arg constructor is only provided if you declare no constructors. 仅当您不声明构造函数时,才提供no-arg构造函数。 So you don't have a problem unless you want a no-arg constructor, but consider it a waste of time writing one. 因此,除非您想要一个无参数的构造函数,否则您不会有任何问题,但是认为这是浪费时间编写一个。

IIRC, C++0x has a way of delegating construction to another constructor. IIRC,C ++ 0x有一种将构造委派给另一个构造函数的方法。 I can't remember the details, but it would allow you to define a no-arg constructor by specifying another constructor, plus the argument(s) to pass to it. 我不记得详细信息,但是它将允许您通过指定其他构造函数以及传递给它的参数来定义无参数构造函数。 Might save typing some data member initializers in some cases. 在某些情况下,可以省去键入某些数据成员初始化程序的时间。 But the default no-arg constructor wouldn't have provided those initializers either. 但是默认的no-arg构造函数也不会提供那些初始化器。

Compiler will generate default copy constructor always, unless you provide your own definition of copy constructor. 除非您提供自己的副本构造函数定义,否则编译器将始终生成默认的副本构造函数。 Your problem is only with default no-arg constructor, which is not generated if there is any constructor definition present. 您的问题仅在于默认的no-arg构造函数,如果存在任何构造函数定义,则不会生成该默认构造函数。 But it's not so hard to provide no-arg constructor which behaves exactly like generated one: 但是提供行为完全类似于生成的no-arg构造器并不难:

class yourClass
{
    public:
       yourClass(){}
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM