我如何...在初始化其他成员时使用不初始化类中的数组的构造函数 [英] How do I...use a constructor that doesn't initialize an array in a class while initializing other members
问题描述
你好再次
我在课堂上遇到数组问题。我已经看过几个这方面的主题,但没有一个能真正解决我的问题。
基本上我需要声明两个类,其中一个类包含另一个类的数组:
class A
{
public:
A(int first) :x(第一个){}
私人:
int x;
};
class B
{
public:
B(int first):y(first){}
私人:
int y;
A attached_As [60];
};
现在我知道你不能在类的构造函数中设置一个数组,即使我没有尝试我得到这个:错误C2512:'A':没有合适的默认构造函数可用
奇怪的是错误指向第一个类。同样奇怪的是,如果类A没有任何成员变量,编译器不会抛出错误。
现在我不需要在构造函数中设置数组。事实上,我有一个完整的算法作为B中的一个方法来做到这一点,但我无法弄清楚为什么我一直得到这个错误。请帮助。
Hello again
I'm having issues with an array in a class. I've seen several topics on this but none of them really addressed my problem.
basically I need to declare two classes with one class holding an array of the other:
class A
{
public:
A(int first):x(first){}
private:
int x;
};
class B
{
public:
B(int first):y(first){}
private:
int y;
A attached_As[60];
};
Now I'm aware that you cannot set an array in a class's constructor yet even if I don't try I get this: error C2512: 'A' : no appropriate default constructor available
strangely the error points to the first class. Also strangely if class A doesn't have any member variables the compiler doesn't throw the error.
Now I don't need to set the array in the constructor. In fact I have an entire algorithm as a method within B to do so, but I can't figure out why I keep getting this error. Please help.
推荐答案
由于一个简单的原因,您会收到此错误。您知道attached_As不是动态数组,因此必须通过CALLING THE CONSTRUCTOR初始化数组中的每个项目。但我们这里有一个问题; A的构造函数有一个构造函数,它接受一个参数。这就是你得到错误的原因。添加默认构造函数以避免错误。
You get this error because of a simple reason. You know that "attached_As" is not a dynamic array and so each item in the array has to be initialized by CALLING THE CONSTRUCTOR. But we have a problem here; the constructor of A has a single constructor which takes one argument. That's the reason why you get the error. Add a default constructor to avoid the error.
class A
{
public:
A() {}
A(int first):x(first){}
private:
int x;
};
class B
{
public:
B(int first):y(first){}
private:
int y;
A attached_As[60];
};
A(){} 是默认构造函数。现在它将编译没有任何错误。
A() {} is the default constructor. Now it'll compile without any error.
这篇关于我如何...在初始化其他成员时使用不初始化类中的数组的构造函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!