类构造函数参数 C++ [英] Class Constructor arguments C++

查看:44
本文介绍了类构造函数参数 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.

  1. 无参数,默认 x 和 y 为零.
  2. 一个论证将 x 赋值,并将 y 默认为零.
  3. 一个参数默认 x 为零并分配 y.我不确定我是否正确设置了课程.我收到以下错误:pair1::pair1(double)pair1::pair1(double) 不能重载.
  1. No arguments, defaults x and y to zero.
  2. One arguement assigns x and defaults y to zero.
  3. 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) and pair1::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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆