1

ここには、x と y の 2 つのプライベート フィールドを持つクラスがあります。

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

Point オブジェクトの初期化で (30,40) が機能しないのはなぜですか?

完全なテスト コードは次のとおりです。

#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
4

3 に答える 3

5

(30, 40) が機能しない理由:

stating(30, 40)は stating と同じではなく、{30, 40}stating(30)は と同じでもありません{30}

(30, 40)コンマ operatorで区切られた一連の式 (この場合は整数リテラル) で、最後の式 (つまり40) に評価されます。一方、{30, 40}使用されるコンテキストでは、集約初期化リストです。

于 2015-10-21T13:56:04.833 に答える
5

コンパイラは(30, 40)、単一の数値に評価されるコンマ演算子を含む式として受け取ります4030が破棄されたことを確認するには、コンパイラの警告をオンにする必要があります。

配列初期化子の括弧で囲まれた式は、コンストラクターの呼び出しではなく、式と見なされます。コンストラクターを明示的に呼び出して、あいまいさを取り除くことができます。

于 2015-10-21T13:58:21.707 に答える