【C++】not accessible because 'Rectangle' uses 'private' to inherit from 'Shape'

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/lyq_12/article/details/84954248

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;
}

正确输出如下:

猜你喜欢

转载自blog.csdn.net/lyq_12/article/details/84954248