创建包含另一个对象的对象

时间:2015-07-17 00:34:04

标签: c++

我正在学习c ++,我对以下情况感到有点困惑:

例如,

类Apple

  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?
  }   

1 个答案:

答案 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.
    }
};