[英]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.