"{ x = a; y = b; }" 在这个 incialization 中做了什么?
What is "{ x = a; y = b; }" doing in this incialization?
我不确定这部分代码的确切用途,我需要在我的研讨会上解释它。
class point {
public:
point( int a = 0, int b = 0 ) **{ x = a; y = b; }**
bool operator ==( const point& o ) { return o.x == x && o.y == y; }
point operator +( const point& o ) { return point( o.x + x, o.y + y ); }
int x, y;
};
{ x = a; y = b; }
是构造函数的复合语句point( int a = 0, int b = 0 );
构造函数重写成
也许会更清楚
point( int a = 0, int b = 0 )
{
x = a;
y = b;
}
因此构造函数的两个参数的默认参数都等于 0。数据成员 x
和 y
在构造函数的复合语句中初始化(使用赋值运算符)。
构造函数可以这样调用
point p1; // x and y are initialized by 0
point p2( 10 ); // x is initialized by 10 and y is initialized by the default argument 0
point p3( 10, 20 ); // x is initialized by 10 and y is initialized by 20
同样的构造函数也可以用下面的方式定义
point( int a = 0, int b = 0 ) : x( a ), y( b )
{
}
我不确定这部分代码的确切用途,我需要在我的研讨会上解释它。
class point {
public:
point( int a = 0, int b = 0 ) **{ x = a; y = b; }**
bool operator ==( const point& o ) { return o.x == x && o.y == y; }
point operator +( const point& o ) { return point( o.x + x, o.y + y ); }
int x, y;
};
{ x = a; y = b; }
是构造函数的复合语句point( int a = 0, int b = 0 );
构造函数重写成
也许会更清楚point( int a = 0, int b = 0 )
{
x = a;
y = b;
}
因此构造函数的两个参数的默认参数都等于 0。数据成员 x
和 y
在构造函数的复合语句中初始化(使用赋值运算符)。
构造函数可以这样调用
point p1; // x and y are initialized by 0
point p2( 10 ); // x is initialized by 10 and y is initialized by the default argument 0
point p3( 10, 20 ); // x is initialized by 10 and y is initialized by 20
同样的构造函数也可以用下面的方式定义
point( int a = 0, int b = 0 ) : x( a ), y( b )
{
}