C++ “{x=a;y=b;}”在这个过程中做了什么?
我不确定这部分代码的确切用途,我需要在研讨会上解释一下C++ “{x=a;y=b;}”在这个过程中做了什么?,c++,class,constructor,initialization,default-constructor,C++,Class,Constructor,Initialization,Default Constructor,我不确定这部分代码的确切用途,我需要在研讨会上解释一下 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
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;
};
是构造函数点int a=0,int b=0的复合语句
如果像这样重写构造函数,可能会更清楚
point( int a = 0, int b = 0 )
{
x = a;
y = b;
}
因此,构造函数的两个参数的默认参数都等于0。在构造函数的复合语句中,使用assignemnt运算符初始化数据成员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 )
{
}
谷歌:什么是C++构造子?它是一个构造函数,它给对象创建了初始值。你真的在学习C++,还没有人告诉你关于构造函数的内容吗?这部分是函数体。谢谢弗拉德,帮了我很多忙:
point( int a = 0, int b = 0 ) : x( a ), y( b )
{
}