简体   繁体   English

没有默认构造函数的类

[英]Classes without default constructors

Can we create an array of objects of the class not having default constructor, if yes then can anyone elaborate on how can we do this? 我们可以创建一个没有默认构造函数的类的对象数组吗?如果可以,那么任何人都可以详细说明如何做到这一点?

For following class for Abc a[10] in main(); 对于main()中Abc a [10]的后续类; is generating compiler error 'no matching function for call to `Abc::Abc()' 正在生成编译器错误“没有匹配函数可调用`Abc :: Abc()'

class Abc{
    private: 
           int x;
    public:
           Abc(int a){
           x = a;
           }
};

int main(){
    Abc a[10]; // Compilation would fail here, as it would look for default constructor
}

Can we create an array of objects of the class not having default constructor? 我们可以创建一个没有默认构造函数的类的对象数组吗?

Yes, you can. 是的你可以。 You have to call one of the available constructors to initialize each of the members of the array. 您必须调用可用的构造函数之一来初始化数组的每个成员。 The only way to do that is to initialize the array with an initialization list: 唯一的方法是使用初始化列表初始化数组:

Abc a[10] = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10};

In this case, it is enough to put integers in the array, because your Abc constructor is not explicit. 在这种情况下,将整数放入数组中就足够了,因为您的Abc构造函数不是显式的。 This means you can do this: 这意味着您可以执行以下操作:

Abc a = 42; // Calls A(42)

If it were explicit, you would have to say 如果明确,则必须说

Abc a[10] = { Abc(1), Abc(2), ..... };

Obviously this dosn't scale well, but it works OK for small arrays. 显然,这种方法无法很好地扩展,但是对于小型阵列而言,它可以正常工作。

The problem is that if you define a constructor, of any kind, the compiler will not automatically generate a default constructor. 问题在于,如果您定义任何类型的构造函数,编译器都不会自动生成默认构造函数。 You have to do it manually. 您必须手动执行。

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

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