1、错误代码
#include <iostream>using namespace std;// 基类class Shape {public:void setWidth(int w){width = w;}void setHeight(int h){height = h;}protected:int width;int height;};// 派生类class Rectangle: Shape{public:int getArea(){ return (width * height); }};int main(void){Rectangle Rect;Rect.setWidth(5);Rect.setHeight(7);cout << "Total area: " << Rect.getArea() << endl;return 0;}
提示错误如下:
2、由于派生类继承基类时“class Rectangle: Shape”,缺少public,导致的问题,修改如下:
#include <iostream>using namespace std;// 基类class Shape {public:void setWidth(int w){width = w;}void setHeight(int h){height = h;}protected:int width;int height;};// 派生类class Rectangle: public Shape{public:int getArea(){ return (width * height); }};int main(void){Rectangle Rect;Rect.setWidth(5);Rect.setHeight(7);cout << "Total area: " << Rect.getArea() << endl;return 0;}
正确输出如下: