如何在对象定义时将值发送给多个构造函数?

How to send value to multiple constructors at object definition?

我有一个简单的程序可以确定圆的半径、面积和周长。我想要三个构造函数:默认构造函数应设置默认值,第一个重载构造函数设置半径值,第二个重载构造函数设置圆心值。

但是,在定义时,我想通过调用其构造函数来定义圆的半径及其圆心。当我尝试做这样的事情时:

Circles sphere(8);
Circles sphere(9,10);

我收到一个有意义的编译器错误:

error: redefinition of 'sphere'

那么如何在对象定义时使用两个不同的构造函数来定义属性呢?

这是我的代码(许多函数因为不相关而被省略):

class Circles    
{
    public:
        Circles (float r);       // Constructor
        Circles();               // Default constructor
        Circles (int, int);              // Constructor for setting the center
    private: 
        float  radius;
        int    center_x;
        int    center_y;
};      

int main()
{
   Circles sphere(8);
   Circles sphere(9,10);

   //...
}

//Implementation section     Member function implementation

Circles::Circles()
{
   radius = 1;
   center_x = 0;
   center_y = 0;
}

Circles::Circles(float r)
{
   radius = r;
}

// Constructor for setting center 
Circles::Circles(int x, int y)
{
   center_x = x;
   center_y = y;
}

谢谢!

问题是您实际上重新定义了 sphere。将第二个变量命名为其他变量。

你不能。构造函数允许您在构造时设置对象的值。
构造完再调用没有意义

要么创建一个构造函数来接收您需要的所有参数。 或者,创建一个API,在构建后更改其他参数。

您可以定义四个构造函数:

Sphere::Sphere() : x(0), y(0), r(1) {}
Sphere::Sphere(double x, double y) : x(x), y(y), r(1) {}
Sphere::Sphere(double r) : x(0), y(0), r(r) {}
Sphere::Sphere(double x, double y, double r) : x(x), y(y), r(r) {}

但这当然不能扩展。

不幸的是,C++ 不支持命名参数,因此唯一的其他选择是先创建对象,然后设置属性(直接或使用 setter)。

您可以尝试使用以下内容模拟命名参数:

Sphere s = Sphere::create()
             .center(10, 20)
             .radius(30)
             .color(255, 0, 0);

但是这在参数数量上线性缩放时需要相当多的代码:

struct Sphere {
    double x, y, r;
    unsigned color;

    Sphere(double x, double y, double r, unsigned color)
        : x(x), y(y), r(r), color(color)
    {
        printf("Building a sphere with "
               "center = (%0.3f, %0.3f) "
               "radius = %0.3f "
               "color = #%06x\n",
               x, y, r, color);
    }

    struct Builder {
        double x, y, r;
        unsigned col;
        Builder() : x(0), y(0), r(1), col(0x000000) {}
        operator Sphere () {
            return Sphere(x, y, r, col);
        }
        Builder& center(double x, double y) {
            this->x = x; this->y = y;
            return *this;
        }
        Builder& radius(double r) {
            this->r = r;
            return *this;
        }
        Builder& color(int r, int g, int b) {
            this->col = (r<<16) | (g<<8) | b;
            return *this;
        }
    };

    static Builder create() { return Builder(); }
};

代码非常重复,在实现大型系统时自动生成构建器可能有意义。