以跨平台方式在C ++中使用复合文字的方式是什么?我知道这是扩展,而不是“官方” C ++,但是必须有一种方法,对吗?
我的结构是:
struct v2 {
int x, y;
};
我想要:
这可行,但非常麻烦:
v2 position = {0,1};
DoSomething(position);
DoSomething( v2 {0,1} );
在MSVC中可用,但在Clang中给出语法错误: error: expected ')'
DoSomething( (v2) {0,1} );
在Clang中可用,但在MSVC cl.exe中给出语法错误: error C4576: a parenthesized type followed by an initializer list is a non-standard explicit type conversion syntax
这在MSVC中有效,但在Clang中是语法错误 error: expected expression
DoSomething( {0,1} );
另外,我以后无法更改该值:
position = v2 {1,1};
可在MSVC中使用,但不适用于Clang: error: expected '(' for function-style cast or type construction
position = (v2) {1,1};
适用于Clang,但不适用于MSVC: error C4576: a parenthesized type followed by an initializer list is a non-standard explicit type conversion syntax
有答案的人吗?
不管是否这样v2
定义(使用所有公共成员变量):
struct v2 {
int x, y;
};
或这样(使用转换构造函数):
class v2 {
public:
v2(int X, int Y) : x(X), y(Y) {}
private:
int x, y;
};
...如果使用C ++ 11或更高版本(clang++ -std=c++11 ...
),则可以像这样使用它:
void DoSomething(const v2& v) {
//... do something ...
}
int main() {
DoSomething({0, 1});
v2 position = {1, 2};
DoSomething(position);
position = {2, 3};
DoSomething(position);
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句