C++ struct初始化

dk1*_*123 8 c++ struct data-structures

以下是我的Sprite类的删节版本:

class Sprite
{
    struct SpriteState {
        Vector3 position;
        int width, height;
        double rotation, scaling;
    };
    std::map<int, SpriteState> stateVector;
}
Run Code Online (Sandbox Code Playgroud)

我想通过一个成员函数创建一个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; }
Run Code Online (Sandbox Code Playgroud)

我收到以下错误:

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

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

但是,在大多数情况下,Sprite仅使用新的位置值进行更新,而宽度,高度,旋转和缩放保持几乎相同 - 这意味着我只在弹出时更改位置值并再次保存上次保存的状态的引用其他价值观.

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

任何可能的实施想法?

yid*_*ing 1

您应该复制 SpriteState,然后修改它:

SpriteState newSpriteState(stateVector.rbegin()->second);
newSpriteState.width = someNewWidth;
return newSpriteState;
Run Code Online (Sandbox Code Playgroud)

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

ClassName(const ClassName&);
Run Code Online (Sandbox Code Playgroud)

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