必须使用member initialization list来初始化的情况

// member initialization
#include <iostream>
using namespace std;

class Circle {
    double radius;
  public:
    Circle(double r) : radius(r) { }
    double area() {return radius*radius*3.14159265;}
};

class Cylinder {
    Circle base;
    double height;
  public:
    Cylinder(double r, double h) : base (r), height(h) {}
    double volume() {return base.area() * height;}
};

int main () {
  Cylinder foo (10,20);

  cout << "foo's volume: " << foo.volume() << '\n';
  return 0;
}

  members shall be initialized in the member initialization list,这个时候,必须使用member initialization list来初始化,因为类中嵌套了另一个类。

foo's volume: 6283.19
posted @ 2019-06-23 21:57  wdliming  阅读(521)  评论(0编辑  收藏  举报