这里有一个带有两个私有字段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对象的数组时,输出正常;否则,输出为0。
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
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句