#include<iostream>
const double PI=3.1415926;
using namespace std;
class Shape
{
public:
Shape(double a ,double b):Area(a),Perimeter(b){}
virtual void Show () const = 0;
protected:
double Area,Perimeter;
static double sum;
};
class Circle:protected Shape
{
public:
Circle(double r):Shape(r*r*PI,2*r*PI),radius(r)
{
sum+=(r*r*PI);
}
void Show () const
{
cout<<"圆形的面积"<<Area<<"圆形的面积"<<Perimeter<<endl;
}
private:
double radius;
};
class Rectangle:protected Shape
{
public:
Rectangle(double a,double b):Shape(a*b,2*(a+b))
{
sum+=(a*b);
}
void Show () const
{
cout<<"矩形的面积"<<Area<<"矩形的面积"<<Perimeter<<endl;
}
private:
double a,b;
};
double Shape::sum=0;
int main()
{
Shape *A;
Circle B(30);
Rectangle C(30,50);
A =&B;
A->Show();
A=&C;
A->Show();
return 0;
}
学习虚函数,但碰到了意外问题,寻之,原来是protected和private的继承类不能通过基类指针对象访问。
因为基类的成员由于protected和private继承访问权限变成了protected和private,访问权限有限制了。
C++虚函数与继承实践
本文通过一个C++示例介绍了虚函数的概念,并探讨了如何在派生类中使用虚函数。文章还讨论了protected和private继承对于基类指针访问的影响。
1093

被折叠的 条评论
为什么被折叠?



