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

标签 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;

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

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 block 范围内。他们是不同的。一旦 if-block 执行,if-block 变量将不复存在(析构)。

只使用一个实例变量。您需要提供函数来设置 值。例如

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

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

关于c++ - 如何将用户输入存储在与默认构造函数中的变量初始化值不同的变量中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30149112/

相关文章:

javascript - 为了获取对象属性标识符而不是属性值?

javascript - 从函数访问 javascript 对象

javascript - 具有多个数组的 JSON 对象

c++ - 使用另一个类中的成员初始值设定项声明一个类的实例

c++ - 在为一个对象调用析构函数时,它被调用了两次?

c++ - 为多字段类重载 operator<

c++ - 在 View 上使用 SELECT 时出现“没有这样的列”错误

c++ - 如何修复类函数 "prototype does not match"和 "cadidate is"错误

c++ - 如何通过指针来识别具体的派生类?

c++ - 显式构造函数及其具有(默认?)值的定义