简体   繁体   中英

c++ how differentiate between base classes in a derived class?

I understand this isn't the best title but I'm not sure how to explain this problem that I'm having without examples.

I have a base class (called vector3)

class vector3 {

    protected:
        double x,y,z;
public:
    vector3(): x(0),y(0),z(0) {}
    vector3(double xin, double yin, double zin): x(xin),y(yin),z(zin) {}
    ~vector3() {}

 //...other stuff

};

Then I have another class, derived from vector3, called vector4:

class vector4 : public vector3 {

protected:
    double ct;
public:

    vector4(): vector3(0,0,0), ct=0 {}

    vector4(double ctin): ct(ctin) {}

    vector4(double ctin, double xin, double yin, double zin):
        vector3(xin, yin, zin), ct(ctin) {}

    vector4(double ctin, vector3 v):
        vector3(v.getx(), v.gety(), v.getz()), ct(ctin) {}

    ~vector4() {}

//...more other stuff

};

And that's all fine, but now I've got a class called particle defined like this:

class particle : public vector4 {
    protected:
        //vector4 r;
        double mass;
        //vector3 beta;
    public:
        particle(): vector4(0,0,0,0), mass=0, vector3(0,0,0) {}

        particle(vector4 rin, double massin, vector3 betain):
            vector4(rin.getx(),rin.gety(),rin.getz(),rin.getct()),
            mass=0,
            vector3(betain.getx(),betain.gety(),betain.getz()) {}

        ~particle() {}
        //...Further stuff
    };

So now the question is:
How do I return the x value, y value and z value of the particle's position, and the x value, y value and z value of the particle's beta vector inside a function in the particle class?

With vector 4 I'd just do:

double getx() const {
    return x;
}
double gety() const {
    return y;
}

etc, but what would I use in the particle's class?

Position and beta vector are attributes of a particle, so you should be using aggregation instead of inheritance:

class particle {
    protected:
        vector4 r;
        double mass;
        vector3 beta;
    // ...

You should only use inheritance where there is an is-a relationship between the subclass and superclass.

In your case, particle is a vector4, so you can define your getters public in vector4, and directly call particle.getX()

However, this does not seem to be a good idea, in my opinion, particle should contain a vector since it is not a specialisation of the vector4 class.

so let's say particle has a vector called _vector

you can define a method like this :

double getX(void) const
{
  return (_vector.getX());
}

Same goes for getY

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM