为什么我不使用此指针就无法返回值?

时间:2018-11-19 16:21:25

标签: c++

#include <iostream>
#include <typeinfo> 
#include <cstdlib> 
using namespace std;

const double pi = 3.141592653589; //#define pi 3.141592653589

template <typename Type>
class CFigure {

protected: 

    Type x , y;

public: 

    CFigure(Type i, Type j) //constructor
    {
        x = i;
        y = j;
    }

    virtual Type Area() = 0; 
};

template <typename Type>
class CTriangle : public CFigure<Type>{

    //protected: int x , y; 

public:

    CTriangle(Type Base, Type Height) : CFigure<Type>(Base , Height) {}

    virtual Type Area();
};

template<typename Type>
Type CTriangle<Type>::Area()
{   **//PROBLEM WITHOUT this** 
    return (this->x * 0.5 * this->y); //base*height/2
}

template <typename Type>
class CRectangle : public CFigure<Type> {

public:
    CRectangle(Type Height, Type Base) : CFigure<Type>(Height, Base) {}

    virtual Type Area() 
    {   **//PROBLEM WITHOUT this** 
        return (this->x * this->y); //base*height
    }
};

template <typename Type>
class CCircle : public CFigure<Type> {

public:

    CCircle(Type Radius, Type Other = 0) : CFigure<Type>(Radius, Other) {}

    virtual Type Area() 
    {   **//PROBLEM WITHOUT this** 
        return (pi * this->x * this->x); //p*r^2
    }
};

CFigure<double> *Factory()
{
    int option = rand() % 3; // 0 ,1 , 2

    switch (option)
    {
    case 0:
    {
        CTriangle<double> *triangle = new CTriangle<double>(5.0, 7.0); 
        return triangle;
    }
    case 1:
    {
        CRectangle<double> *rectangle = new CRectangle<double>(9.0, 6.0); 
        return rectangle;
    }
    case 2:
    {
        CCircle<double> *circle = new CCircle<double>(7.0); //radius = 7
        return circle;
    }
    }
}

int main()
{
    CFigure<double> *objects;

    int numOfTriangles = 0; //triangles
    int numOfRectangles = 0; //rectangles
    int numOfCircles = 0; //circles

    //RTTI
    for (register int i = 0; i < 20; i++)//20 objects
    {
        objects = Factory(); 

        cout << "Object " << i << " is: " << typeid(*objects).name() << ".  ";

        if (typeid(*objects) == typeid(CTriangle<double>)) 
        {
            numOfTriangles++;
        }

        if (typeid(*objects) == typeid(CRectangle<double>)) 
        {
            numOfRectangles++;
        }

        if (typeid(*objects) == typeid(CCircle<double>)) 
        {
            numOfCircles++;
        }

        cout << "Area is" << objects->Area() << endl;
    }

    cout << endl;

    cout << "Objects generated:\n";
    cout << "Triangles: " << numOfRectangles << endl;
    cout << "Rectangles: " << numOfRectangles << endl;
    cout << "Circles: " << numOfCircles << endl;

    cout << "Exit..." << endl;

    return 0;

}
  

我的问题是,为什么在我的纯虚拟机的每个实现中   函数,如果我不使用(this)指针,我得到一个错误?我的书,用   一个类似的示例,以显示RTTI。当我在ide(VS2017)上输入x或y时   清楚地说(x,y)受保护,但是当我运行它时,我得到一个   错误,无法识别x和y,并且(可以)正常工作

0 个答案:

没有答案