Candidate::Candidate ()
{
}
它没有做任何事情。 不按原样编写无法执行该行:
Candidate *list = new Candidate [10];
为什么?
Error: no default constructor exists for the class "Candidate"
最佳答案
要允许动态数组分配,new Candidate[10]
,Candidate
的默认构造函数必须可用。也就是说,它必须能够不带任何参数。如果您为 Candidate
提供任何您自己的构造函数,无论它们采用多少参数,通常由编译器自动定义的隐式默认构造函数都不会被定义。因此你必须自己提供它,即使它的 body 是空的。见§12.1/5:
A default constructor for a class
X
is a constructor of classX
that can be called without an argument. If there is no user-declared constructor for classX
, a constructor having no parameters is implicitly declared as defaulted (8.4).
你的类会很好,因为编译器将隐式定义一个默认的默认构造函数:
class Candidate
{ }; // Compiler provides a default constructor
但是一旦你给它任何其他构造函数,就不再提供隐式默认构造函数:
class Candidate
{
public:
Candidate(int x);
// A user-defined constructor is provided so the default constructor
// must be defined explicitly
};
关于c++ - 制作动态对象数组问题?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13662423/