【发布时间】:2017-05-13 15:21:48
【问题描述】:
我得到了这段代码,想知道为什么在 Class Cylinder 中有一行
Cylinder(double r, double h) : base (r), height(h) {}
不是
Cylinder(double r, double h) : base.radius (r), height(h) {}
我的意思是一个 double 被移交并且 base 是一个 Cylinder,它不应该是 base.radius 吗?
// 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;
}
【问题讨论】:
-
没有继承或派生对象?
-
其实不用,因为需要调用基类的(唯一的)构造函数!
-
您是否对
base的命名感到困惑? -
您在考虑 C# 中的
base关键字吗?它在 C++ 中不存在。 -
你为什么回滚我的编辑?如前所述,不涉及派生!再次投反对票,让您的问题再次不清楚。
标签: c++ class constructor