基类指针
本帖最后由 wgqyjh 于 2013-12-25 15:23:29 编辑 代码如下:
#include <iostream>
using namespace std;
class Shape
{
public:
virtual double const GetArea() {return 0.0;}
virtual double const GetPerimeter() {return 0.0;}
virtual double const GetVolume() {return 0.0;}
virtual void ShapeName() = 0;
};
class Point : public Shape
{
public:
Point(double = 0,double = 0);
void setPoint(double,double);
double GetX() const { return x;}
double GetY() const { return y;}
virtual void ShapeName() { cout << "Point:";}
friend ostream & operator <<(ostream &,const Point &);
protected:
double x,y;
};
Point::Point(double a,double b){ x = a; y = b;}
void Point::setPoint(double a, double b){x = a; y = b;}
ostream & operator <<(ostream &output,const Point &p)
{
output << "[" << p.x << "," << p.y << "]";
return output;
}
class Circle:public Point
{
public:
Circle(double = 0,double = 0,double = 0);
double GetRadius() const;
void setRadius(double);
virtual void ShapeName() { cout << "Circle";}
virtual double GetArea() const;
virtual double GetPerimeter() const;
friend ostream & operator <<(ostream &, const Circle &);
protected:
double radius;
};
Circle::Circle(double a,double b,double r):Point(a,b),radius(r){}
double Circle::GetPerimeter() const {return 2 * 3.14 * radius;}
void Circle::setRadius(double r){radius = r;}
double Circle::GetArea() const {return 3.14*radius*radius;}
ostream & operator <<(ostream & output, const Circle &c)
{
output << "[" << c.x << "," << c.y << "],r = " << c.radius;
return output;
}
void main()
{
Point point(3.2,2.1);
Circle circle(3.3,4.2,5.1);
point.ShapeName();
cout << point << endl;
circle.ShapeName();
cout << circle << endl;
Shape *ptr;
ptr = &point;
cout << ptr->GetArea();
}
ptr->GetArea() 输出结果是0 ptr指针没有指向point?
[解决办法]
Shape *ptr;
ptr = &point;
cout << ptr->GetArea();
没看到你Point有重载GetArea啊,只有Circle有重载这个API
[解决办法]
基类和子类同一个函数const放的位置不同,这两者含义就一样了
[解决办法]
基类GetArea的const也放在后面
[解决办法]
virtual double GetArea() const {return 0.0;}
virtual double const GetArea() {return 0.0;}