C ++使用枚举和,更改变量的值

时间:2014-10-17 14:02:50

标签: c++

我的家庭作品“使用C ++”中有这个问题:

问:根据评论的要求完成以下程序,然后显示输出。

 #include <iostream>

 using std::cout;

 using std::cin;

 using std::endl;

// Define an enumerated datatype Language

// Its legal values are german,english,spanish,and turkish 

 int main()

 {

 /* Define a varaible lang of type Language  */

 /* Set the varaible lang with the value german */

 /* Write a statement to print the value of the varaible lang */

 /* Change the value of the varible lang to turkish */



 return 0; 
} // end main
  • 我写过这样的代码。

    #include <iostream>
    
    
     using std::cout;
    
    
    #include <iostream>
    using std::cout;
    
    using std::cin;
    
    using std::endl;
    
     // Define an enumerated datatype Language
     // Its legal values are german,english,spanish,and turkish 
    
    
     enum language { german, english, spanish, turkish };
    
     int main()
     {
     enum language { german, english, spanish, turkish };   
     /* Define a varaible lang of type Language  */
      language lang;
       /* Set the varaible lang with the value german */
       lang=german;
     /* Write a statement to print the value of the varaible lang */
       cout<<lang <<endl;
     /* Change the value of the varible lang to turkish */
       lang=turkish;
       cout<<lang<<endl;
     return 0;
    
     } // end main
    

我试着回答,但我能做的就是:$

确定我的回答是假的,  我真的无法理解这些部分:

/ *将变量lang的值更改为turkish * / !!

我想知道如何解决这些问题,请帮帮我吗? :$

谢谢。

1 个答案:

答案 0 :(得分:0)

在作业的评论中写有

  

定义枚举数据类型语言

因此,您必须使用名称Language而不是language

在您的程序中,您定义了两个具有相同名称的枚举。函数main中的最后一个声明在全局命名空间中隐藏了具有相同名称的声明。很明显,不需要定义两个枚举。其中一个你可以删除。

你可以写例如

#include <iostream>

enum Language { german, english, spanish, turkish };

int main() 
{ 
    /* Define a varaible lang of type Language */ 
    Language lang; 

    /* Set the varaible lang with the value german */ 
    lang = german; 

    /* Write a statement to print the value of the varaible lang */ 
    std::cout << lang << std::endl;

    /* Change the value of the varible lang to turkish */ 
    lang = turkish; 
}

您可以在更改变量lang后添加输出语句。

//...
    /* Change the value of the varible lang to turkish */ 
    lang = turkish; 

    std::cout << lang << std::endl;
}