抱歉这篇文章的标题太长了。但是,我相信它总结了我遇到的问题。我有一个默认构造函数,每次调用对象时都会设置这些默认值:
Circles::Circles()
{
radius = 1;
center_x = 0;
center_y = 0;
}
但是,我想为用户提供输入他们自己的值的选项。这意味着必须以某种方式忽略 radius
、center_x
和 center_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;
我想将 rad
、x
和 y
传递给这个重载的构造函数:
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);
SetX
和SetY
方法将(应该)设置任何已构造实例的成员变量值。
关于c++ - 如何将用户输入存储在与默认构造函数中的变量初始化值不同的变量中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30149112/