For a derived class with a constructor that takes a base class pointer, how do I refer to the base class pointer?

StackOverflow https://stackoverflow.com/questions/22541789

I'm working on an assignment on abstract base classes for shapes. For the last section we need to write a class which is a general 3D version of any of the prior 2D shapes eg. square.

So as you can see from my code below, its constructor takes a base class pointer shape*. In my function "getVolume" I basically need to multiply z by the area of the shape pointed to by shape*, which can be calculated by a function getArea() which is specified in each shapes respective class. But do I refer to the shape that is being pointed to?

class prism : public square, public rectangle, public circle {
private:
    double z;
public:
    prism(){z=0;}
    prism(shape*, double a){z=a;}
    ~prism(){cout<<"Prism destructor called"<<endl;}

    //Access functions
    void print_(){cout<<"Prism with length = "<<z;}
    double getLength(int n)const{ return z; }
    void setLength(double a){z=a;}

    //Other functions
    double getVolume(){ return ??????????;}

    };

How do I refer to the shape that is being pointed to? I was hoping it would be something like this->getArea() or shape*->getArea() but I just get errors that tell me "shape does not refer to a value" etc.

Can anyone offer some assistance?

有帮助吗?

解决方案

shape is a class type not an object. You should keep the pointer to shape in Your constructor. It should be like:

Your class member:

shape * theShape;

And your constructor:

prism(shape* sh, double a)
{
    z=a;
    theShape =sh;
}

And your getVolume() should be like:

double getVolume(){ return theShape->getArea()*z;}

其他提示

I may be reading your question wrong but you don't seem to be using the shape*. So you could add a member in your class:

shape* s_;

prism(shape* s, double a) s_(s) ...

And then call s_->getArea().

Yeah sorry this was a fairly stupid question, but an easy mistake to make i guess. As you say I needed to add a shape* as a member of my prism class which I could then refer to in my constructor. For anyone running into a similar confusion here is what I believe a class of this sort should look like!

class prism : public ...(reference 'shapes')..... {
private:
    double z;
    shape* s;
public:   
    prism(shape* s_, double a){z=a; s=s_;}

    double doSomethingToShape(){return s->doSomething();}

};
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top