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

时间:2015-05-10 08:04:14

标签: c++ class object constructor default-constructor

对不起这篇文章的冗长标题。但是,我相信它总结了我遇到的问题。我有一个默认构造函数,每次调用一个对象时都会设置这些默认值:

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;

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

  

圆的半径为1圆的中心为(0,0)

为什么会这样?

1 个答案:

答案 0 :(得分:1)

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

它在两个不同的范围创建局部变量sphere2(好像分成两个不同的函数)。一个在函数范围,另一个在if-block范围。它们是不同的。只要if-block被执行,if-block变量就会停止存在(destruct)。

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

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

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