相遇
两条平行线

A pure virtual function is a function declared in a base class that has no definition relative to the base. As a result, any derived class must define its own version—it cannot simply use the version defined in the base. To declare a pure virtual function, use this general form: virtual type func-name(parameter-list) = 0.

If a class has at least one pure virtual function, then that class is said to be abstract. An abstract class has one important feature: there can be no objects of that class. To prove this to yourself, try removing the override of area( ) from the Triangle class in the preceding program. You will receive an error when you try to create an instance of Triangle.

/*TwoDshape.h */---base class                        

 #include <iostream>

#include <cstring>

using namespace std;

class TwoDshape

{

protected:

double width;

double height;

char name[20];

public:

TwoDshape(void);

TwoDshape(double w, double h,char *n);

TwoDshape(double x,char *n);

void ShowDim();

double GetWidth();

double GetHeight();

char* GetName();

virtual double Area()=0;

};

/*TwoDshape.cpp*/

TwoDshape::TwoDshape(void)

{

width=height=0.0;

strcpy(name,"unknow");

}

 

TwoDshape::TwoDshape(double w, double h,char *n)

{

width=w;

height=h;

strcpy(name,n);

}

TwoDshape::TwoDshape(double x,char *n)

{

width=height=x;

strcpy(name,n);

}

void TwoDshape::ShowDim()

{

cout<<"width and height are:"<<width<<" and "<<height;

}

double TwoDshape::GetWidth()

{

return width;

}

double TwoDshape::GetHeight()

{

return height;

}

char* TwoDshape::GetName()

{

return name;

}

/*Triangle*/---derived class

 #include "TwoDshape.h"

class Triangle: public TwoDshape

{

char style[20];

public:

Triangle()

{

strcpy(style,"unknown");

}

Triangle(char *str,double w,double h):TwoDshape(w,h,"triangle")

{

width=w;

height=h;

strcpy(style,str);

}

Triangle(double x):TwoDshape(x,"triangle")

{

width=height=x;

strcpy(style,"isosceles");

}

double Area()

{

return GetWidth()*GetHeight()/2;

}

};

 

/*Main*/

 #include "Triangle.h"

#include <iostream>

using namespace System;

int main(array<System::String ^> ^args)

{

char ch;

TwoDshape *shape=&Triangle("right",8.0,12.0);

cout<<shape->GetName();

cout<<shape->Area();

cin>>ch;

return 0;

}

posted on 2009-04-30 15:33  张凤娟  阅读(304)  评论(0编辑  收藏  举报