【发布时间】: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