开发者

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

开发者 https://www.devze.com 2023-04-06 17:28 出处:网络
I have a class Sphere that inherits from class Shape (for a homework project): Within Shape I have three constructors.The declarations from Shape.h are as follows:

I have a class Sphere that inherits from class Shape (for a homework project):

Within Shape I have three constructors. The declarations from Shape.h are as follows:

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

Within Sphere my constructors inherit from these constructors. The declarations in my Sphere.h file are as follows:

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

My syntax here is based largely on looking at templates. While my first language was C++, I was unfortunately taught other concepts, like inheritance, only in Java.

An开发者_开发问答yway, I have the following error messages upon `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’

Can you help me understand these messages and what might be causing them? I first tried letting them be expressed in the typical way, i.e., instead of

Sphere(): Shape();

and then describing the constructor itself in the .cc file, I did as I had seen done in some online tutorials, without really understanding why:

Sphere(): Shape() {}

This didn't change anything, the problem remained. Thanks for your help!


You need to specify names, not just types, for the parameters, and pass the names, not the types. For example:

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


You haven't given your constructor arguments any names.

This is ok, so long as you don't actually want to use those arguments!


Your initialization list belongs in the constructor's implementation and isn't part of the constructor's declaration (or prototype). You seem to be putting it with both.

You can either do:

// Sphere.h
struct Sphere {
  Sphere();
};

// Sphere.cpp
Sphere::Sphere() : Shape() {

}

Or you can do:

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

// Sphere.cpp
// No constructor here; you defined it in the header.
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号