0
對不起,本文的冗長標題。不過,我相信它總結了我所遇到的問題。我有一個默認的構造函數,將每一個對象被調用時,這些默認值:如何將用戶輸入存儲在與默認構造函數中的變量初始化值不同的變量中?
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;
最後,我們遇到了打印默認值的問題:
圓的半徑爲1的圓的圓心爲(0,0)
這究竟是爲什麼?
太棒了!謝謝。我一直在想,爲什麼沒有人在不同的範圍內創建對象,就好像它是一個更動態的過程。 – jshapy8
你可以。如果你使用動態分配。要麼通過自己分配內存,要麼使用智能指針。 – Ajay