簡體   English   中英

C ++簡單程序初學者

[英]Beginner in c++ simple program

大家好,我正在嘗試學習類和對象的基礎知識。 據我所知,我的語法是正確的,但是我在程序中收到了這些錯誤消息...

錯誤:范圍中未聲明“ A”

錯誤:范圍中未聲明“ a”

錯誤:范圍中未聲明“ UIClass”

錯誤:范圍中未聲明“ AgeObject”

錯誤:預期為“;” 在“ NameObject”之前

錯誤:范圍內未聲明“ NameObject”

錯誤:預期為“;” 在“ ResultObject”之前

錯誤:范圍內未聲明“ ResultObject”

#include <iostream>
#include <string>
 using namespace std;

class UI{

public:

void Age(){
int a;
cout << "Age?" << endl;
cin >> a;}

void Name(){
string A;
cout << "Name" << endl;
cin >> A;}

void Results(){
cout << "Your name is " << A << "and you are " << a << " years old." << endl;
 }


};


int main ()

{

cout << "Enter Your Name and Age?" << endl;

UIClass; AgeObject;
AgeObject.Age();

UIClass NameObject;
NameObject.Name();

UIClass ResultObject;
ResultObject.Results();

return 0;

}

因此,在您的代碼的Results方法中,您試圖訪問未在其中聲明的變量。

所以你有了:

void age()
{
    // does stuff with age
} 

void name()
{
    // does stuff with name
}

變量僅存在於這些方法中。 因此,當您嘗試從Results()獲取它們時,會出現“超出范圍”錯誤。

因此,您可以做的是聲明四個其他方法setAge和setName,這些方法將采用以下參數:

class UI
{
    private:
        int age;
        string name;

    public:
        void setAge(int ag)
        {
            age = ag;
        }

        int getAge()
        {
            return age;
        }

然后,將您的void age()方法更改為如下所示:

void age()
{
    // Do the stuff you've already done
    setAge(a);
}

然后,當您嘗試完成輸出時:

cout << "Your name is " << getName() << " and you are " << getAge() << " years old." << endl;

您使用的是哪本書,他們確實應該已經解釋了這類內容。 如果沒有,我會換一個新的。 這是您將用C ++編寫的最基本的程序之一。

我沒有給您完整的答案,但這應該會鼓勵您並為您提供一個起點。 希望對您有幫助。

快樂的編碼。

錯誤明確表明變量聲明超出范圍。 變量int astring A在函數內部聲明,當您嘗試使用該函數以外的變量時,它們不在范圍內。 聲明為類的公共變量。 另外,您已經實例化了3個UI對象來調用三個函數,因此不要這樣做,因為每個對象都有自己的內存。 實例化一個對象並調用函數。

 class UI
   {

     public:
     int a;
     string A;
     void Age()
     {
       //int a;  remove the local varaible,  'a' can't be used outside function Name
       cout << "Age?" << endl;
       cin >> a;
     }

     void Name()
     {
       //string A;  remove the local varaible, 'A' can't be used outside function Name
       cout << "Name" << endl;
       cin >> A;
     }

      void Results()
      {
        cout << "Your name is " << A << "and you are " << a << " years old." << endl;
      }   

    };

您已將aA聲明a NameAge方法的局部變量,因此它們在Results方法中不可用。 您可能想讓它們成為成員變量。 將它們的聲明移到類范圍而不是方法范圍。 另外, aA是有史以來最差的名字!

然后,您聲明該類的三個單獨的實例(除非您在類和實例名稱之間添加了分號),然后在不同的實例上調用每個方法。 嘗試創建一個實例,並在其上調用所有三個方法。

哦,請請學習如何縮進代碼...

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM