在c ++中创建一个类实例的向量

maz*_*lor 5 c++ class

我创建了一个类,其名称为Student,如下所示:

class Student
{
 private:
     unsigned int id;                                // the id of the student 
public:   
    unsigned int get_id(){return id;};   
    void set_id(unsigned int value) {id = value;};
    Student(unsigned int init_val) {id = init_val;};   // constructor
    ~Student() {};                                     // destructor
};
Run Code Online (Sandbox Code Playgroud)

然后我想要一个容器(比如一个矢量),它的元素是类Student的实例,但我发现自己无法理解这种情况,这是我的问题:

首先我运行此代码:

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

const unsigned int N = 5;

Student ver_list[2] = {7, 9};


int main()
{

  cout<< "Hello, This is a code to learn classes"<< endl;

  cout<< ver_list[1].get_id() << endl;

return 0;
}
Run Code Online (Sandbox Code Playgroud)

一切都很好,输出是:

Hello, This is a code to learn classes
9
Run Code Online (Sandbox Code Playgroud)

现在,当我尝试这些选项时:

选项1:

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

const unsigned int N = 5;

vector <Student> ver[N];             // Create vector with N elements
for(unsigned int i = 0; i < N; ++i )
ver[i].set_id(i); 


int main()
{

  cout<< "Hello, This is a code to learn classes"<< endl;

  cout<< ver[1].get_id() << endl;

return 0;
}
Run Code Online (Sandbox Code Playgroud)

我得到了这个输出"错误":

test.cpp:26:3: error: expected unqualified-id before 'for'
   for(unsigned int i = 0; i < N; ++i )
   ^
test.cpp:26:27: error: 'i' does not name a type
   for(unsigned int i = 0; i < N; ++i )
                           ^
test.cpp:26:34: error: expected unqualified-id before '++' token
   for(unsigned int i = 0; i < N; ++i )
                                  ^
test.cpp: In function 'int main()':
test.cpp:43:15: error: 'class std::vector<Student>' has no member named 'get_id'

 cout<< ver[1].get_id() << endl;
               ^
Run Code Online (Sandbox Code Playgroud)

选项#2:

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

const unsigned int N = 5;

Student ver[N];                       // Create one dimensional array with N elements
for(unsigned int i = 0; i < N; ++i )
   ver[i].set_id(i); 


int main()
{

  cout<< "Hello, This is a code to learn classes"<< endl;

  cout<< ver[1].get_id() << endl;

return 0;
}
Run Code Online (Sandbox Code Playgroud)

输出"错误"是:

test.cpp:30:14: error: no matching function for call to 'Student::Student()'
Student ver[5];
             ^
test.cpp:30:14: note: candidates are:
test.cpp:14:2: note: Student::Student(unsigned int)
  Student(unsigned int init_val) {id = init_val;};   // constructor
  ^
test.cpp:14:2: note:   candidate expects 1 argument, 0 provided
test.cpp:7:7: note: Student::Student(const Student&)
 class Student
       ^
test.cpp:7:7: note:   candidate expects 1 argument, 0 provided
test.cpp:31:1: error: expected unqualified-id before 'for'
 for(unsigned int i = 0; i < N; ++i )
 ^
test.cpp:31:25: error: 'i' does not name a type
 for(unsigned int i = 0; i < N; ++i )
                         ^
test.cpp:31:32: error: expected unqualified-id before '++' token
 for(unsigned int i = 0; i < N; ++i )
                                ^
Run Code Online (Sandbox Code Playgroud)

在第一次尝试时,一切都看起来不错,但是当我尝试下两个选项时,我收到错误,我希望我能理解我在做什么错.

谢谢.

Mar*_*ork 16

这个:

vector <Student> ver[N];
Run Code Online (Sandbox Code Playgroud)

创建一个N元素数组.每个元素都是vector<Student>.这不是你想要的.您可能正在尝试创建N元素向量.这个语法是:

vector <Student> ver(N);
Run Code Online (Sandbox Code Playgroud)

但是你不能使用它,因为你的类没有默认的构造函数.因此,您的下一个选择是初始化具有相同元素的所有对象.

vector <Student> ver(N, Student(0));
Run Code Online (Sandbox Code Playgroud)

你还尝试创建一个像这样的学生阵列:

Student ver[N];
Run Code Online (Sandbox Code Playgroud)

这不行.因为它尝试使用默认构造函数初始化数组中的每个元素.但是你的类没有默认的构造函数.所以这不会奏效.但这就是你的原始代码确实有效的原因:

Student ver_list[2] = {7, 9};  // Here you are using the constructor for your object.
                               // It uses the normal constructor you provided not the default one.
Run Code Online (Sandbox Code Playgroud)

其他问题是您无法在函数(方法)之外运行代码.
所以这不起作用:

for(unsigned int i = 0; i < N; ++i )
    ver[i].set_id(i); 
Run Code Online (Sandbox Code Playgroud)

在C++ 11中,您可以像数组一样初始化向量:

vector<Student>  ver = { 0, 1, 2, 3, 4, 5};
Run Code Online (Sandbox Code Playgroud)

如果你没有C++ 11或初始化更复杂.然后你需要写一个包装器.

class VecWrapper
{
     public:
         std::vector<Student>   ver;
         VecWrapper()
         {
            ver.reserve(N);
            for(unsigned int i = 0; i < N; ++i )
                ver.push_back(Student(i));
         }
 };
Run Code Online (Sandbox Code Playgroud)

现在您可以将它放在全局范围内,它将自动初始化.

 VecWrapper   myData;  // myData.vec  initializaed before main entered.

 int main()
 {}
Run Code Online (Sandbox Code Playgroud)

完整解决方案

选项2:

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

const unsigned int N = 5;

// The following is not correct
// This creates an arrya of `N` elements each element is `vector <Student>`
//
// vector <Student> ver[N];             // Create vector with N elements
// 

// The following lines are not allowed.
// All code has to be inside a function.
//
// for(unsigned int i = 0; i < N; ++i )
// ver[i].set_id(i); 


// What you want is:
//    I use the following because it is unclear if you have C++11 or not.  
class VecWrapper
{
   public:
     std::vector<Student>   vec;
     VecWrapper()
     {
        vec.reserve(N);
        for(unsigned int i = 0; i < N; ++i )
            vec.push_back(Student(i));
     }
};
VecWrapper   myData;  // myData.vec 
int main()
{

  cout<< "Hello, This is a code to learn classes"<< endl;

  cout<< myData.vec[1].get_id() << endl;

return 0;
}
Run Code Online (Sandbox Code Playgroud)