类构造函数参数 C++
我正在为 x 和 y 笛卡尔坐标系创建一个 pair1 类.x 和 y 是双精度值.我需要有 3 个构造函数.
I am creating a pair1 class for a x and y Cartesian coordinate system. x and y are doubles. I need to have 3 constructors.
- 无参数,默认 x 和 y 为零.
- 一个论证将 x 赋值,并将 y 默认为零.
- 一个参数默认 x 为零并分配 y.我不确定我是否正确设置了课程.我收到以下错误:
pair1::pair1(double)
和pair1::pair1(double)
不能重载.
- No arguments, defaults x and y to zero.
- One arguement assigns x and defaults y to zero.
- One arugeument defaults x to zero and assigns y. I'm not sure if I am setting up the class right. I get the follwing error:
pair1::pair1(double)
andpair1::pair1(double)
cannot be overloaded.
我的班级:
class pair1
{
private:
double x;
double y;
public:
pair1(){ x = 0.0, y = 0.0; }
pair1( double a ){ x = a; y =0.0; }
pair1(double b){ x = 0.0; y = b; }
};
1) 无参数,默认 x 和 y 为零.
1) no arguments, defaults x and y to zero.
这很简单
2) 一个论证赋值 x 并且默认 y 为零.
2) one arguement assigns x and defaults y to zero.
3) 一种方法默认 x 为零并分配 y.
3) one arugeument defaults x to zero and assigns y.
这是个问题.当您只有一个参数时,您怎么知道应该调用这两个参数中的哪一个?这就是您收到编译错误的原因.
That's a problem. How do you know, when you only have one parameter, which of the two is meant to be called? That's why you get a compilation error.
相反 - 如果需要,使用默认构造函数(没有参数的构造函数)、完整构造函数(具有两者的构造函数)以及 SetX()
和 SetY()
分别设置 X 和 Y,并通过函数名称进行区分.
Instead - use the default constructor (the one with no parameters), full constructor (the one with both), if needed, and SetX()
and SetY()
to set the X and Y separately, and make distinction by the name of the function.
class pair1
{
private:
double x;
double y;
public:
pair1( double a=0.0, double b=0.0 ){ x = a; y =b; };
// default value 0.0 allows to only
// set x, and leave y to be the default,
// or leave them both default.
void SetX(double a) { x=a;};
void SetY(double b) { y=b;};
};