繁体   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