您是否应该在复杂数据类型上使用访问器?这是一个例子:
说我有一个Player
课程,里面有一个Sprite
对象。假设Sprite
对象具有setPosition()
访问器方法。现在假设我想通过播放器调用该方法,因此我在Sprite
中创建了Player
对象的访问器。
class Player
{
public:
const Sprite& getSprite() const;
private:
Sprite sprite;
}
现在假设我创建了一个'播放器'对象,如何在setPosition
上调用sprite
?我不能只说playerObject.getSprite().setPosition();
,因为Sprite
方法返回的getSprite()
引用是const。
考虑到sprite
对象是否有针对其所有成员的保护,我是否应该在这种情况下公开sprite
对象?或者这是一种不好的做法,我确实需要使用访问者?
答案 0 :(得分:0)
没有好的答案:
有2D点:
class Point {
public:
// Skipping constructors here.
int x() const { return m_x; }
int x&() { return m_x; }
int y() const { return m_y; }
int y&() { return m_y; }
private:
int m_x;
int m_y;
};
与相比,看起来有点过分
struct Point {
int x;
int y;
};
第一个允许您将内部数据(假设)更改为std :: vector,第二个数据结构不允许更改。即便是第一个也很麻烦,我更喜欢(但这是一个品味问题)