【问题标题】:Why does the second variable not change in the field?为什么字段中的第二个变量没有变化?
【发布时间】:2019-07-24 13:51:40
【问题描述】:

我正在为我的讲座测试一些程序。我正在创建类并使用参数列表来初始化一个字段,但第二个变量没有改变。

#include <iostream>
using namespace std;

class Punkt {

    int x;
    int y;

public:
    Punkt(int a = 0, int b = 0)
    {
        x = a;
        y = b;

    }
    void printXY()
    {
        cout << "x= " << x << " y= " << y << endl;
    }
};

int main() {

    Punkt pFeld[] = { (1, 1), (2, 2), (3, 3) };

    for (int i = 0; i < 3; i++)
        pFeld[i].printXY();
    cin.get();
};

没有错误消息。预期结果是 x 和 y 变化,而实际结果是只有 x 变化,y 保持为 0。

【问题讨论】:

  • Punkt pFeld[] = { {1, 1}, {2, 2}, {3, 3} };
  • 打开你的编译器警告,例如,在 gcc I get the following message: warning: left operand of comma operator has no effect [-Wunused-value] Punkt pFeld[] = { (1, 1), (2, 2), (3, 3) };
  • (1,1) 是一个给出1 结果的表达式,而不是一对值的表示。因此Punkt 的构造函数被传递给参数a 的单个值,以及参数b 的默认值(0)。使用{} 而不是()

标签: c++ constructor initializer-list comma-operator


【解决方案1】:

这个

(1, 1)

是一个带有逗号运算符的表达式。

其实这个初始化

Punkt pFeld[] = { (1, 1), (2, 2), (3, 3) };

等价于

Punkt pFeld[] = { 1, 2, 3 };

所以第二个默认参数等于0的构造函数被调用了3次。

改为使用

{ 1, 1 }

这是您的更新代码

#include <iostream>
using namespace std;

class Punkt {

    int x;
    int y;

public:
    Punkt(int a = 0, int b = 0)
    {
        x = a;
        y = b;

    }
    void printXY()
    {
        cout << "x= " << x << " y= " << y << endl;
    }
};

int main() {

    Punkt pFeld[] = { {1, 1}, {2, 2}, {3, 3} };

    for (int i = 0; i < 3; i++)
        pFeld[i].printXY();
    cin.get();
}

它的输出是

x= 1 y= 1
x= 2 y= 2
x= 3 y= 3

注意main函数后面的分号是多余的。

【讨论】:

    【解决方案2】:

    (1, 1) 传递给Punkt 的构造函数,comma operator 将返回第二个操作数作为结果(第一个操作数被丢弃),因此您只传递了一个值为1int给构造函数。这就是为什么y 总是初始化为0

    你想要的应该是

    Punkt pFeld[] = { {1, 1}, {2, 2}, {3, 3} }; // list initialization since C++11
    

    Punkt pFeld[] = { Punkt(1, 1), Punkt(2, 2), Punkt(3, 3) };
    

    【讨论】:

      猜你喜欢
      • 2020-01-19
      • 2019-10-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-06-28
      • 1970-01-01
      • 1970-01-01
      • 2017-08-18
      相关资源
      最近更新 更多