簡體   English   中英

C ++中的構造函數可能存在歧義

[英]A possible ambiguity of constructor in C++

#include <iostream>
using namespace std;

struct A {
    A(int i) {
        cout << "1 args" << endl;
    }
    A(int i, int j) {
        cout << "2 args" << endl;
    }
};

void foo(int i) {
    cout << "1 args" << endl;
}
void foo(int i, int j) {
    cout << "2 args" << endl;
}

int main() {
    int i, j;
    A(i, j);
    (A)(i, j);
    foo(i, j);
    (foo)(i, j);
}

輸出:

2 args
1 args
2 args
2 args

我知道結果“ 1 args”是因為“(i,j)”被評估為“ j”。

但是考慮到構造函數也是函數,差異的原因是什么?

構造函數是成員函數; 如果您想像其他函數一樣嘗試“調用構造函數”,則代碼可能是aA(i,j); 使用上的一些對象的成員訪問運算符a ,你已經創建。 但這是不允許的,因為構造函數僅在對象創建過程中被調用。

  1. A(i, j); 匹配語法postfix-expression: simple-type-specifier ( expression-list ) 該語法的含義是創建該類型的prvalue表達式,其中expression-list是構造函數參數。

  2. (A)(i, j); 與該語法不匹配,因為無法對simple-type-specifier進行括號。 然而,它確實匹配cast-expression ,所以它是表達(i, j)轉換為(這是一個逗號運算表達式) A 在這種情況下,強制轉換為類類型的結果涉及構造該類類型的臨時類。

  3. foo(i, j); 匹配postfix-expression: postfix-expression ( expression-list ) ,這是使用該參數列表對函數foo的調用

  4. (foo)(i, j); 也匹配相同的規則,因為( postfix-expression )仍然是postfix-expression

對於那些尋求較少技術答案的人,我將閱讀MM答案,例如:

A是一種類型,foo不是 ,因此:

(A)(i, j);    // cast to A the result of (i, j) ==> calls A(j) in conversion
(foo)(i, j)   // still the same as foo(i, j)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM