簡體   English   中英

在C ++中用括號初始化數組對象

[英]Initialization of Array Objects With Parenthesis in C++

這里有一個帶有兩個私有字段x和y的類;

class Point
{
private:
    int x, y;
public:
    Point(int = 1,int = 1);
    void move(int, int);
    void print()
    {
        cout << "X = " << x << ", Y = " << y << endl;
    }
};

當按如下所示初始化Point對象的數組時,輸出正常。

Point array1[] = { (10), (20), { 30, 40 } };

輸出;

First array
X = 10, Y = 1
X = 20, Y = 1
X = 30, Y = 40

但是,如果我們按如下所示初始化Point數組,則輸出是奇怪的;

Point array2[] = { (10), (20), (30, 40) }; 

輸出;

Second array
X = 10, Y = 1
X = 20, Y = 1
X = 40, Y = 1

為什么(30,40)不能用於Point對象的初始化?

這是完整的測試代碼;

#include <iostream>
using namespace std;

class Point
{
private:
    int x, y;
public:
    Point(int = 1,int = 1);
    void move(int, int);
    void print()
    {
        cout << "X = " << x << ", Y = " << y << endl;
    }
};

Point::Point(int x, int y)
{
    cout << "..::Two Parameter Constructor is invoked::..\n";
    this->x = x;
    this->y = y;
}

void Point::move(int x, int y)
{
    this->x = x;
    this->y = y;
}

int main()
{
    // Point array1[] = { Point(10), Point(20), Point(30, 40) };
    // Use parenthesis for object array initialization;
    Point array1[] = { (10), (20), { 30, 40 } };    // curly bracket used for two parameter
    Point array2[] = { (10), (20), (30, 40) };      // paranthesis used for all objects

    cout << "First array" << endl;
    for (int i = 0; i < 3; i++)
        array1[i].print();

    cout << "Second array" << endl;
    for (int i = 0; i < 3; i++)
        array2[i].print();

    return 0;
}

並完整輸出測試代碼;

..::Two Parameter Constructor is invoked::..
..::Two Parameter Constructor is invoked::..
..::Two Parameter Constructor is invoked::..
..::Two Parameter Constructor is invoked::..
..::Two Parameter Constructor is invoked::..
..::Two Parameter Constructor is invoked::..
First array
X = 10, Y = 1
X = 20, Y = 1
X = 30, Y = 40
Second array
X = 10, Y = 1
X = 20, Y = 1
X = 40, Y = 1

為什么(30,40)無法運作:

陳述(30, 40)與陳述{30, 40}不相同,陳述(30){30}也不相同。

(30, 40)是由逗號運算符分隔的表達式序列(在這種情況下為整數),其結果為最后一個表達式(即40 )。 而在所使用的上下文中, {30, 40}是一個聚合初始化列表

編譯器使用(30, 40)作為帶有逗號運算符的表達式,該運算符的結果為單個數字40 您應該打開編譯器警告以發現30被丟棄。

數組初始值設定項中帶括號的表達式被視為表達式,而不是構造函數調用。 您可以顯式調用構造函數以消除歧義。

代碼中的括號導致您感到困惑。 當您編寫(10)這並不意味着調用參數為10的構造函數。 (10)變為10,您可以使用

Point array1[] = { 10, 20, { 30, 40 } };

所以對於第二個數組

(30, 40)

因此使用逗號運算符

 { 10, 20, (30, 40) }

成為

 { 10, 20, 40 }

如果要調用兩個參數的構造函數,則必須像第一個示例一樣將其括起來,或顯式調用構造函數

{ 10, 20, Point(30, 40) }

暫無
暫無

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

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