我正在学习c ++,我对以下情况感到有点困惑:
例如,
class Apple
{
int kg;
Apple();
}
class Fruit
{
private:
int count;
Apple one;
public:
Fruit();//do we need to call the constructor for apple,
//or the default Fruit constructor calls it as well?
}
答案 0 :(得分:1)
在您的示例中,将调用默认构造函数。例如,如果apple构造函数将int作为第一个参数,则必须通过初始化列表进行设置:
class Apple
{
public:
int kg;
Apple(int _kg) :
kg(_kg)
{}
};
class Fruit
{
private:
int count;
Apple one;
public:
Fruit() : one(5) //right here or you'll get an error
{
this->count = 5;
//this->one(5) doesn't work.
}
};