2015-05-10 13 views
0

對不起,本文的冗長標題。不過,我相信它總結了我所遇到的問題。我有一個默認的構造函數,將每一個對象被調用時,這些默認值:如何將用戶輸入存儲在與默認構造函數中的變量初始化值不同的變量中?

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

不過,我想給用戶選擇輸入自己的價值觀。這意味着必須以某種方式忽略默認值radius,center_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
if (toupper(enter) == 'Y') 
     Circles sphere2(rad, x, y); 
    Circles sphere2; 

它在兩個不同的範圍創建局部變量sphere2(好像成兩個不同的功能)。一個在功能範圍,另一個在if-block範圍。他們是不同的。 if-block一旦執行,塊變量將不再存在(破壞)。

僅使用一個實例變量。您需要提供Set這些值的功能。例如

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

方法SetXSetY將(應該)任何已構建的實例的集成員變量的值。

+0

太棒了!謝謝。我一直在想,爲什麼沒有人在不同的範圍內創建對象,就好像它是一個更動態的過程。 – jshapy8

+0

你可以。如果你使用動態分配。要麼通過自己分配內存,要麼使用智能指針。 – Ajay

相關問題