类的继承
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
1 #include<iostream.h> 2 const double PI=3.14159265; 3 class Circle 4 { 5 protected: 6 double radius; 7 public: 8 9 Circle(double r){radius=r;}; 10 virtual double area(){return 0.0; }; 11 virtual double volume(){return 0.0;}; 12 }; 13 14 class Sphere:public Circle //qiu ti 15 {public: 16 17 Sphere(double r):Circle(r){} 18 double area(){return 4*PI*radius*radius;}; 19 double volume(){return 4*PI*radius*radius/3.0; }; 20 }; 21 22 class Column:public Circle //zhu ti 23 { public: 24 Column(double r,double h):Circle(r){ height=h;} 25 double area(){return 2*PI*radius*(radius+height);}; 26 double volume(){ return PI*radius*radius*height;}; 27 private: 28 double height; 29 30 }; 31 32 33 void main() 34 { 35 Circle *p; 36 Sphere subj(1); 37 p=&subj; 38 cout<<"球体面积:"; 39 cout<<p->area()<<endl; 40 cout<<"球体体积:"; 41 cout<<p->volume()<<endl; 42 43 Column object(2,3); 44 p=&object; 45 cout<<"柱体面积:"; 46 cout<<p->area()<<endl; 47 cout<<"柱体体积:"; 48 cout<<p->volume()<<endl; 49 50 }
这是我写的段代码一段关于类的普通继承的一个例子:经过我自身学习并打出这段代码是一般会遇到一下这些错误:
1、把这些代码: Circle(double r){radius=r;};
virtual double area(){return 0.0; };
virtual double volume(){return 0.0;};
写成这样: Circle(double r){radius=r;};
virtual double area(){};
virtual double volume(){};这会显示error 因为没有返回值 return;有时候会因为lose {} 显示error;还望各位与我一样的初学者要注意一下!
2、 在继承父类的时候 class Sphere:public Circle 这语句 要彻记 没有括号的,还有这两句: Sphere subj(1); 取地址符这没括号 p=&subj;
3、