试图为继承类的子类编写构造函数,猜测语法,期望的主表达式错误

Attempting to write constructors for subclass inheriting from class, guessing at syntax, expected-primary-expression error?

本文关键字:语法 期望 错误 表达式 继承 子类 构造函数      更新时间:2023-10-16

我有一个类Sphere继承自类Shape(用于家庭作业项目):

在Shape中我有三个构造函数。Shape.h中的声明如下:

Shape();
Shape(Vector);
Shape(Vector, float[]);

在Sphere中,我的构造函数继承自这些构造函数。我的Sphere.h文件中的声明如下:

Sphere(): Shape() {}//line 17
Sphere(Vector, float): Shape(Vector) {}//line 18
Sphere(Vector, float, float[]): Shape(Vector, float[]) {}//line 19

我这里的语法主要是基于查看模板。虽然我的第一门语言是c++,但不幸的是,我只在Java中学习了其他概念,比如继承。

无论如何,我在' make'上有以下错误消息:

Sphere.h: In constructor ‘Sphere::Sphere(Vector, float)’:
Sphere.h:18: error: expected primary-expression before ‘)’ token
Sphere.h: In constructor ‘Sphere::Sphere(Vector, float, float*)’:
Sphere.h:19: error: expected primary-expression before ‘,’ token
Sphere.h:19: error: expected primary-expression before ‘float’

你能帮我理解这些消息以及可能导致它们的原因吗?我首先尝试用典型的方式来表达它们,即,而不是

Sphere(): Shape();

,然后在。cc文件中描述构造函数本身,我做了我在一些在线教程中看到的,没有真正理解为什么:

Sphere(): Shape() {}

这并没有改变什么,问题仍然存在。谢谢你的帮助!

您需要为参数指定名称,而不仅仅是类型,并传递名称,而不是类型。例如:

Sphere(Vector a, float b, float[] c): Shape(a, c) {}

您还没有给构造函数参数指定任何名称。

这是可以的,只要你实际上不想使用这些参数!

初始化列表属于构造函数的实现,而不是构造函数声明(或原型)的一部分。你似乎两者都有。

你可以做:

// Sphere.h
struct Sphere {
  Sphere();
};
// Sphere.cpp
Sphere::Sphere() : Shape() {
}

或者你可以这样做:

// Sphere.h
struct Sphere {
  Sphere() : Shape() { }
};
// Sphere.cpp
// No constructor here; you defined it in the header.