试图为继承类的子类编写构造函数,猜测语法,期望的主表达式错误
Attempting to write constructors for subclass inheriting from class, guessing at syntax, expected-primary-expression error?
我有一个类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.
相关文章:
- 1d 智能指针不适用于语法 (*)++
- 助记符和指向成员语法的指针
- 有人能分解一下这个c++模板的语法吗
- C++避免重复声明的语法是什么
- QMetaObject invokeMethod的基于函数指针的语法
- 这个语法std::class<>{}(arg1, arg2) 在C++中是什么意思?
- 为什么包含windows.h会产生语法错误,从而阻止类的实例化?(C2146,C2065)
- 从类型std::函数传递变量失败,尽管调用方期望的类型完全相同
- 单独定义模板化嵌套类方法的正确语法
- 共享指针和具有自定义删除程序的唯一指针之间的语法差异背后的任何原因
- 错误 C2760:语法错误:映射迭代器上意外的标记"标识符",预期的";"
- 为什么我会收到错误 C2143 语法错误:缺少"*"之前的';'?
- 一元*运算符的操作数是否期望一个 prvalue
- 奇怪的代码抛出编译错误模板< J,int aSize=10> C2143:语法错误:在"<"之前缺少";"
- 使用基类指针调用基类的值构造函数的语法是什么?
- 很好的语法来获取对向量/数组数据的大小引用?
- C++语法运算符功能?
- C++使用 rand 定义函数语法
- 语法错误,意外的标记,期望文件结束
- 试图为继承类的子类编写构造函数,猜测语法,期望的主表达式错误