8

以下是我的 Sprite 类的精简版:

class Sprite
{
    struct SpriteState {
        Vector3 position;
        int width, height;
        double rotation, scaling;
    };
    std::map<int, SpriteState> stateVector;
}

我想通过一个看起来类似于以下内容的成员函数创建一个 SpriteState 对象:

SpriteState newSpriteState(
        Vector3 position = stateVector.rbegin()->second.position, 
        int width = = stateVector.rbegin()->second.width, 
        int height = = stateVector.rbegin()->second.height, 
        double rotation = stateVector.rbegin()->second.rotation, 
        double scaling = stateVector.rbegin()->second.scaling)
    { SpriteState a; a.position = position; a.width = width; a.height = height; a.rotation = rotation; a.scaling = scaling; return a; }

我收到以下错误:

非静态成员引用必须相对于特定对象

类本身背后的基本思想是在精灵发生变化时存储它的各种状态,以便我可以在需要时轻松恢复到以前的状态。

然而,在大多数情况下,Sprite 仅使用新的位置值更新,而宽度、高度、旋转和缩放几乎保持不变 - 这意味着我只在弹出并再次保存上次保存的状态的引用时更改位置值其他值。

因此,我希望能够为函数设置默认值,这样我就不必费力地重复编写相同的值。

关于实施的任何可能的想法?

4

4 回答 4

2

重载它:

SpriteState newSpriteState(Vector3 position)
{
    return newSpriteState(
            position,
            stateVector.rbegin()->second.width, 
            stateVector.rbegin()->second.height, 
            stateVector.rbegin()->second.rotation, 
            stateVector.rbegin()->second.scaling)      
}
于 2012-12-19T11:09:42.117 回答
2

默认参数在调用者的上下文中进行评估,因此如果您需要访问类的成员以获取“默认”值,则不能使用默认参数。

另一方面,您可以使用重载来获得相同的效果:

SpriteState newSpriteState(
    Vector3 position,
    int width,
    int height,
    double rotation,
    double scaling)
{ 
    SpriteState a; 
    a.position = position; 
    a.width = width; 
    a.height = height; 
    a.rotation = rotation; 
    a.scaling = scaling; 
    return a; 
}

SpriteState newSpriteState(
    Vector3 position)
{
    return newSpriteState(position,
                          stateVector.rbegin()->second.width, 
                          stateVector.rbegin()->second.height, 
                          stateVector.rbegin()->second.rotation, 
                          stateVector.rbegin()->second.scaling);
}
/* ... And similar for additional non-default values. */
于 2012-12-19T11:24:20.597 回答
1

成员函数不能调用类成员。您可以通过执行以下操作将其存档:

SpriteState newSpriteState(SpriteState sprite_state)        
{ 
  SpriteState a; 
  a.position = position; 
  a.width = width; 
  a.height = height; 
  a.rotation = rotation; 
  a.scaling = scaling; 
  return a; 
}

然后你在另一个中调用这个函数member function

newSpriteState(stateVector.rbegin()->second);
于 2012-12-19T11:52:32.903 回答
1

您应该复制 SpriteState,然后对其进行修改:

SpriteState newSpriteState(stateVector.rbegin()->second);
newSpriteState.width = someNewWidth;
return newSpriteState;

默认情况下,每个结构和类都具有以下形式的复制构造函数:

ClassName(const ClassName&);

默认情况下复制类/结构中的数据。

于 2012-12-19T11:07:11.447 回答