备选方案1,重用临时变量:
Sticker sticker;
sticker.x = x + foreground.x;
sticker.y = foreground.y;
sticker.width = foreground.width;
sticker.height = foreground.height;
board.push_back(sticker);
sticker.x = x + outline.x;
sticker.y = outline.y;
sticker.width = outline.width;
sticker.height = outline.height;
board.push_back(sticker);
Run Code Online (Sandbox Code Playgroud)
备选方案2,确定临时变量的范围:
{
Sticker sticker;
sticker.x = x + foreground.x;
sticker.y = foreground.y;
sticker.width = foreground.width;
sticker.height = foreground.height;
board.push_back(sticker);
}
{
Sticker sticker;
sticker.x = x + outline.x;
sticker.y = outline.y;
sticker.width = outline.width;
sticker.height = outline.height;
board.push_back(sticker);
}
Run Code Online (Sandbox Code Playgroud)
备选方案3,直接写入矢量存储器:
{
board.push_back(Sticker());
Sticker &sticker = board.back();
sticker.x = x + foreground.x;
sticker.y = foreground.y;
sticker.width = foreground.width;
sticker.height = foreground.height;
}
{
board.push_back(Sticker());
Sticker &sticker = board.back();
sticker.x = x + outline.x;
sticker.y = outline.y;
sticker.width = outline.width;
sticker.height = outline.height;
}
Run Code Online (Sandbox Code Playgroud)
你更喜欢哪种方法?
编辑:为了便于讨论,假设必须在构造函数之外逐个进行赋值
小智 16
我的选择 - 给Sticker一个带参数的构造函数.然后:
board.push_back( Sticker( outline.x, foo.bar, etc. ) );
Run Code Online (Sandbox Code Playgroud)
编辑:用于说明构造函数参数名称的代码:
#include <iostream>
using namespace std;
struct S {
int a, b;
S( int a, int b ) : a(a), b(b) {
}
};
int main() {
S s( 1, 2);
cout << s.a << " " << s.b << endl;
}
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
1726 次 |
最近记录: |