【问题标题】:c++ dynamic array and classesC++ 动态数组和类
【发布时间】:2020-07-22 10:16:35
【问题描述】:

我正在尝试在我的作业中创建动态。但每次我调试时,我都会不断得到数组需要是一个常量。我该如何解决。首先,我使用 Visual Studio。这是为了上课。

我的代码是

 int main()
    {
        int stdno;

        cout << "Enter number of Students :" << endl;
        cin >> stdno;

        Student s1[stdno];

        for (int i = 0; i < stdno; i++)
        {

            s1[i].inputStudentInfo();
        }
        cout << "" << endl;
        cout << "-------------STUDENT DETAILS------------------" << endl;

        for (int i = 0; i < stdno; i++)
        {
            s1[i].displayStudentInfo();
            s1[i].computeAvgScore();
        }

        return 0;
    }

【问题讨论】:

  • Student s1[stdno];(可变长度数组或 VLA)不是标准 C++。你应该改用std::vector

标签: c++ arrays class dynamic


【解决方案1】:
Student s1[stdno];

这在 C++ 中不是标准的。您可以使用动态内存分配。

Student *s1 = new Student[stdno];

delete [] s1;

或者你可以简单地使用

std::vector<Student> student_vec;

【讨论】:

    【解决方案2】:

    如果您需要动态(运行时大小)数组,您应该更喜欢使用 std::vector

    std::vector<Student> s1(stdno);
    

    然后您的其余代码将按照编写的方式工作。

    【讨论】:

      【解决方案3】:

      我不断得到数组需要是一个常量

      在程序运行之前,数组大小需要是编译时间常数。

      它们是动态的替代品,例如std::vector

      int main()
      {
          int stdno;
      
          cout << "Enter number of Students :" << endl;
          cin >> stdno;
      
          std::vector<Student> s1(stdno);
      
          for (int i = 0; i < stdno; i++)
          {
      
              s1[i].inputStudentInfo();
          }
          cout << "" << endl;
          cout << "-------------STUDENT DETAILS------------------" << endl;
      
          for (int i = 0; i < stdno; i++)
          {
              s1[i].displayStudentInfo();
              s1[i].computeAvgScore();
          }
      
          return 0;
      }
      

      您也可以使用动态数组分配,但动态分配是一门高级主题。这是它的外观示例:

      auto s1 = new Student[stdno];
      
      // ...
      
      delete[] s1;
      

      【讨论】:

      • 好的,如果我添加 std::vector 我得到命名空间 std 没有成员。突然 s1 现在是未定义的。
      • @TonyLaValle 你#include &lt;vector&gt;了吗?
      猜你喜欢
      • 1970-01-01
      • 2012-06-19
      • 2018-09-11
      • 1970-01-01
      • 2018-01-13
      • 2016-03-18
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多