[英]What clause in the C++11 Standard does allow me to eliminate the `A` in the `return` statement in the `A::operator-()` below?
C ++ 11标准中的哪个子句可以让我在下面的A::operator-()
中的return
语句中消除A
? 换句话说,如果我替换表达式,则return A{-ai, -aj};
通过return {-ai, -aj};
该代码可以编译并正确执行。 如果可能,我想知道如何使用标准?
#include <iostream>
struct A {
int i;
int j;
A(int n, int m) : i(n), j(m) {}
};
A operator-(A a) { return A{-a.i, -a.j}; }
int main()
{
A a(1, 2);
A b = -a;
std::cout << b.i << " " << b.j << '\n';
}
6.6.3 / 2
带有括号初始化列表的return语句通过从指定的初始化列表中进行复制列表初始化(8.5.4)初始化要从函数返回的对象或引用。 [ 示例:
std::pair<std::string,int> f(const char* p, int x) { return {p,x}; }
—结束示例 ]
在C ++标准的8.5.4节的列表初始化的第3段中对此进行了描述。
—否则,如果T是类类型,则考虑构造函数。 列举了适用的构造函数,并通过重载决议(13.3、13.3.1.7)选择了最佳的构造函数。 如果需要变窄的转换(请参见下文)以转换任何参数,则程序格式错误。
完下面有个例子
struct S {
// no initializer-list constructors
S(int, double, double); // #1
S(); // #2
// ...
};
S s1 = { 1, 2, 3.0 }; // OK: invoke #1
S s2 { 1.0, 2, 3 }; // error: narrowing
S s3 { }; // OK: invoke #2
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.