开发者

SomeClass* initialEl = new SomeClass[5];

开发者 https://www.devze.com 2023-01-07 03:19 出处:网络
Should SomeClass* initialEl = new SomeClass[5]; necessarily compile, assuming SomeClass does not have a non-publicly declared default constructor?Consider:

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()
{
    S开发者_如何学ComeClass* initialEl = new SomeClass[5];

    delete[] initialEl;

    return 0;
}


Assuming SomeClass has a publicly accessible default constructor, yes.

Note that there is a difference between

  1. having a publicly accessible default constructor (what i said) and
  2. not having a non-publicly declared default constructor (what you said)

For the following class 2. is true but 1. is not:

class A {
    SomeClass(const SomeClass&) {}
};

This is due to §12.1/5 (C++03):

If there is no user-declared constructor for class X, a default constructor is implicitly declared. An implicitly-declared default constructor is an inline public member of its class.


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:

class A {
public:
    SomeClass(int) {}
    SomeClass() {}
};

Or let another constructor qualify as a default constructor:

class A {
public:
    SomeClass(int=0) {}
};


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消