类构造函数参数C ++ [英] Class Constructor arguments 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;};
};
这篇关于类构造函数参数C ++的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!