如何将用户输入存储在与默认构造函数中的变量初始化值不同的变量中?

How to store user input in variable that is a different value than in the variable initialization in default constructor?

抱歉,这个 post 的标题太长了。但是,我相信它总结了我遇到的问题。我有一个默认构造函数,每次调用 object 时都会设置这些默认值:

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

但是,我想为用户提供输入他们自己的值的选项。这意味着必须以某种方式忽略 radiuscenter_xcenter_y 的默认值。我这样设置提示:

char enter;    // for user selection
    float rad = 1; // for user selection
    int x = 0, y = 0;     // for user selection

    cout << "Would you like to enter a radius for sphere2? (Y/N): ";
    cin.get(enter);

    if (toupper(enter) != 'N')
    {
        cout << "Please enter a radius: ";
        cin >> rad;
    }

    cout << endl;

    cout << "Would you like to enter a center for sphere2? (Y/N): ";
    cin.clear();
    cin.ignore();
    cin.get(enter);

    if (toupper(enter) != 'N')
    {
        cout << "Please enter x: ";
        cin >> x;
        cout << "Please enter y: ";
        cin >> y;
    }

    cout << endl << endl;

    if (toupper(enter) == 'Y')
        Circles sphere2(rad, x, y);
   Circles sphere2;

我想将 radxy 传递给这个重载的构造函数:

Circles::Circles(float r, int x, int y)
{
   radius = r;
   center_x = x;
   center_y = y;
}

这是将输出发送到屏幕的方式:

cout << "Sphere2:\n";
cout << "The radius of the circle is " << radius << endl;
cout << "The center of the circle is (" << center_x 
    << "," << center_y << ")" << endl;

最后,我们得到了打印默认值的问题:

The radius of the circle is 1 The center of the circle is (0,0)

为什么会这样?

if (toupper(enter) == 'Y')
        Circles sphere2(rad, x, y);
   Circles sphere2;

它在两个不同的范围内创建局部变量 sphere2(就像在两个不同的函数中一样)。一个在函数范围内,另一个在 if 块范围内。它们是不同的。一旦 if-block 执行,if-block 变量将不复存在(破坏)。

只使用一个实例变量。您需要为 Set 值提供函数。例如

Circles sphere;
sphere.SetX(x);
sphere.SetY(y);

方法SetXSetY 将(应该)设置任何已构造实例的成员变量值。