SomeClass* 初始El = new SomeClass[5];
应该 SomeClass*initialEl = new SomeClass[5];假设 SomeClass 没有非公开声明的默认构造函数,是否必须编译?考虑:
/*
* SomeClass.h
*
*/
#ifndef SOMECLASS_H_
#define SOMECLASS_H_
class SomeClass
{
public:
SomeClass(int){}
~SomeClass(){}
};
#endif /* SOMECLASS_H_ */
/*
* main.cpp
*
*/
#include "SomeClass.h"
int main()
{
SomeClass* initialEl = new SomeClass[5];
delete[] initialEl;
return 0;
}
Should SomeClass* initialEl = new SomeClass[5]; necessarily compile, assuming SomeClass does not have a non-publicly declared default constructor? Consider:
/*
* SomeClass.h
*
*/
#ifndef SOMECLASS_H_
#define SOMECLASS_H_
class SomeClass
{
public:
SomeClass(int){}
~SomeClass(){}
};
#endif /* SOMECLASS_H_ */
/*
* main.cpp
*
*/
#include "SomeClass.h"
int main()
{
SomeClass* initialEl = new SomeClass[5];
delete[] initialEl;
return 0;
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
假设
SomeClass
有一个可公开访问的默认构造函数,是的。之间存在差异,
对于以下类 2. 为 true 但 < em>1. 不是:
这是由于 §12.1/5 (C++03):
通过您的更新,
SomeClass
没有默认构造函数。您没有声明一个构造函数,并且因为您声明了另一个构造函数,所以编译器也不会隐式声明它。如果你需要一个,你必须自己实现它:
或者让另一个构造函数有资格作为默认构造函数:
Assuming
SomeClass
has a publicly accessible default constructor, yes.Note that there is a difference between
For the following class 2. is true but 1. is not:
This is due to §12.1/5 (C++03):
With your update,
SomeClass
doesn't have a default constructor. You didn't declare one and because you have declared another constructor the compiler won't declare it implicitly either.If you need one you have to implement it yourself:
Or let another constructor qualify as a default constructor:
不,如果没有默认构造函数,它就无法编译。在这种情况下,没有编译器生成的默认构造函数,因为您已经定义了另一个构造函数。 “如果需要并且用户尚未声明其他构造函数,编译器将尝试生成一个构造函数。” -- C++ 编程语言,Stroustrup
如果您确实想使用
new SomeClass[5]
,您还必须提供一个默认构造函数。No, it won't compile without a default constructor. There is no compiler-generated default constructor in this case, because you have defined another constructor. "The compiler will try to generate one if needed and if the user hasn't declared other constructors." -- The C++ Programming Language, Stroustrup
If you really want to use
new SomeClass[5]
, you'll have to provide a default constructor as well.