main.cpp
//main.cpp #include "Point.h" #include "circl.h" #include "Cyl.h" #include "iostream" using namespace std; int main() { Point p1; p1.display(); Point p2(10,10); p2.display(); p2.change_vale(5,5); p2.display(); Circle c1; c1.display(); c1.change_vale(3,2,1); c1.display(); Cyl s1; s1.display(); s1.change_vale(4,5,6,7); s1.display(); getchar(); getchar(); return 0; }
point.h
//point.h //#ifndef POINT_H //#define POINT_H 0 #pragma once class Point { public: Point(); Point(float ,float ); void change_vale(float,float); virtual void display(); protected: float x;float y; }; //#endif
point.cpp
//point.cpp /* class Point { public: Point(); Point(float ,float ); virtual void change_vale(float,float); virtual void display(); protected: float x,float y; };*/ #include "point.h" #include "iostream" using namespace std; //这一行如果没有,编译不通过。 Point::Point() { x=0;y=0; } Point::Point(float a,float b) { x=a; y=b; } void Point::change_vale(float a,float b) { x=a; y=b; } void Point::display() { cout<<"x="<<x<<"y="<<y<<endl; }
circle.h
#include "point.h" #pragma once //#ifndef CIRCLE_H //circl.h //#define CIRCLE_H class Circle:public Point { public: Circle(); Circle(float,float,float); void change_vale(float,float,float); virtual void display(); protected: float r; }; //#endif
circle.cpp
//circle.cpp /* class Circle:public Point { public: Circle(); Circle(float); void change_vale(float); virtual void display(); protected: float r; };*/ #include "circl.h" #include "iostream" using namespace std; Circle::Circle() { x=0;y=0;r=1; } Circle::Circle(float a,float b,float rr):Point(a,b),r(rr){} void Circle::change_vale(float a,float b, float n) { x=a; y=b; r=n; } void Circle::display() { cout<<x<<" "<<y<<" "<<" "<<r<<endl; }
cyl.h
//cyl.h #pragma once #include "circl.h" class Cyl:public Circle { public: Cyl(); Cyl(float ,float,float,float); void change_vale(float ,float,float,float); void display(); protected: float h; };
cyl.cpp
//cyl.cpp /* class Cyl:public Circle { public: Cyl(); Cyl(float ,float,float,float); void change_vale(float ,float,float,float); void display(); protected: float h; };*/ #include "cyl.h" #include "iostream" using namespace std; Cyl::Cyl() { x=0;y=0;r=2;h=10; } Cyl::Cyl(float a,float b,float rr,float hh):Circle(a,b,rr),h(hh){} void Cyl::change_vale(float a,float b,float rr,float hh) { x=a;y=b;r=rr;h=hh; } void Cyl::display() { cout<<x<<" "<<y<<" "<<r<<" "<<h<<endl; }
tips:
1.函数宏包含命令需要的结构格式。
main()包含三个头文件,三个.h文件由继承方向依次包含。
把被继承的文件写在最前,注释掉,方便下面书写。养成习惯。
注意using namespace std,iostream的书写位置。(函数实现时候需要包含iostream)
2.重复包含的错误。=》重要。参照另一博客
http://blog.csdn.net/followingturing/archive/2010/05/24/5620312.aspx
在代码较多的程序中,按照这个模板能够较大降低难度,增强程序的可读性。