主题:[原创]指向类函数成员的指针来实现虚函数的多态性
[size=3]#include <iostream>
using namespace std;
class shape
{
public:
virtual double area()=0;
};
class square:public shape
{
protected:
double H;
public:
square(double h)
{
H=h;
}
double area()
{
return H*H;
}
};
class circle:public square
{
private:
const double PI;
public:
circle(double r):square(r),PI(3.1415)
{
}
double area()
{
return H*H*PI;
}
};
class triangle:public square
{
protected:
double W;
public:
triangle(double h,double w):square(h)
{
W=w;
}
double area()
{
return W*H/2.0;
}
};
void print(shape *s[],int n)
{
double shape::*p()=shape::area;
int i;
for(i=0;i<n;i++)
{
cout<<"shape"<<i+1<<"的面积是:"<<(s[i].*p)()<<endl;
}
}
int main()
{
shape *s[6];
s[0]=new square(5);
s[1]=new circle(8);
s[2]=new triangle(5,8);
s[3]=new square(6);
s[4]=new circle(10);
s[5]=new triangle(6,10);
print(s,6);
return 0;
} [/size]
无法通过编译,各位大虾帮帮忙
using namespace std;
class shape
{
public:
virtual double area()=0;
};
class square:public shape
{
protected:
double H;
public:
square(double h)
{
H=h;
}
double area()
{
return H*H;
}
};
class circle:public square
{
private:
const double PI;
public:
circle(double r):square(r),PI(3.1415)
{
}
double area()
{
return H*H*PI;
}
};
class triangle:public square
{
protected:
double W;
public:
triangle(double h,double w):square(h)
{
W=w;
}
double area()
{
return W*H/2.0;
}
};
void print(shape *s[],int n)
{
double shape::*p()=shape::area;
int i;
for(i=0;i<n;i++)
{
cout<<"shape"<<i+1<<"的面积是:"<<(s[i].*p)()<<endl;
}
}
int main()
{
shape *s[6];
s[0]=new square(5);
s[1]=new circle(8);
s[2]=new triangle(5,8);
s[3]=new square(6);
s[4]=new circle(10);
s[5]=new triangle(6,10);
print(s,6);
return 0;
} [/size]
无法通过编译,各位大虾帮帮忙