我正在练习训练 C++,问题是:
a) 在“my_game”命名空间中,创建一个头文件,其中定义了一个类 “矩形”,必须具有受保护的访问级别成员数据: • 矩形中心点的二维坐标; • 矩形的宽度和高度。 b) 在另一个头文件中,仍然在“my_game”命名空间内,定义一个类 “CollisionBox”,派生自基类“Rectangle”。 此类必须包含私有成员数据: • 布尔变量“hit_”,指示是否与另一个对象发生碰撞 “碰撞箱”。 该类还必须提供具有公共访问级别的成员函数: • “ComputeCollision”:检测是否存在碰撞(实施碰撞检测 AABB) 与另一个对象。如果发生碰撞,将更改成员数据“hit_”的值 在这两个对象中,返回值true,它也应该在控制台打印一个 通知存在碰撞的消息。 • “hit”:返回存储在“hit_”成员数据中的值。
我创建了文件,然后我做了这个:
在我称为 Geometry.h 的文件中,我创建了矩形类
#pragma once
namespace my_game {
class Rectangle {
protected:
float central_x;
float central_y;
float rect_height;
float rect_width;
};
}
在一个名为 Physics.h 的文件中,我创建了继承自矩形的 CollisionBox 类
#pragma once
#include "Geometry.h"
namespace my_game {
class CollisionBox : public Rectangle{
private:
bool hit_ = false;
public:
bool Compute_Collision(Rectangle rect1, Rectangle rect2) {
if (rect1.central_x < rect2.central_x + rect2.rect_width &&
rect1.central_x + rect1.rect_width > rect2.central_x &&
rect1.central_y < rect2.central_y + rect2.rect_height &&
rect1.central_y + rect1.rect_height > rect2.central_y) {
return true;
}
else {
return false;
}
}
};
}
但这让我出错:无法通过对象或指针访问受保护的成员。 我在这里做错了什么?受保护的成员不应该通过继承访问?