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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/19657728/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-27 23:01:44  来源:igfitidea点击:

create a vector of instances of a class in c++

c++class

提问by mazlor

i created a class its name is Student as follows:

我创建了一个名为 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
};

then after i wanted to have a container ( say a vector ) its elements are instances of class Student, but i found myself not able to understand this situation , here is my issue:

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

first i run this code:

首先我运行这个代码:

#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;
}

everything is fine and the output is :

一切都很好,输出是:

Hello, This is a code to learn classes
9

now when i try these options:

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

option #1:

选项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;
}

i got this output "error" :

我得到了这个输出“错误”:

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;
               ^

option #2:

选项#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;
}

the output "error" was :

输出“错误”是:

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 )
                                ^

In the first try everything was looking ok , but when i tried the two next options , i received errors , i wish that i can understand what wrong i am doing.

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

Thanks.

谢谢。

回答by Martin York

This:

这个:

vector <Student> ver[N];

Creates an array of Nelements. Each element is vector<Student>. This is not you want. You were probably trying to create a vector of Nelements. The syntax for this is:

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

vector <Student> ver(N);

But you can't use this because your class does not have a default constructor. So your next alternative is to initializae all the objects with the same element.

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

vector <Student> ver(N, Student(0));

You also tried to create an array of students like this:

您还尝试创建一组像这样的学生:

Student ver[N];

This will not work. Because it tries to initialize every element in the array with the default constructor. But your class does not have a default constructor. So this will not work. But this is why your original code did work:

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

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.

The other issues is that you can not run code outside a function(method).
So this will not work:

另一个问题是您不能在函数(方法)之外运行代码。
所以这行不通:

for(unsigned int i = 0; i < N; ++i )
    ver[i].set_id(i); 

In C++11 you can initialize a vector the same way as an array:

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

vector<Student>  ver = { 0, 1, 2, 3, 4, 5};

If you don't have C++11 or initialization is more complex. Then you need to write a wrapper.

如果您没有 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));
         }
 };

Now You can place this in global scope and it will auto init.

现在你可以把它放在全局范围内,它会自动初始化。

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

 int main()
 {}

Full solution:

完整解决方案:

Option 2:

选项 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;
}

回答by Zach Stark

The main problem is you are trying to execute a for loop at global scope. It is acceptable to define and initialize variables outside of a function, but using a for loop or assignment operator is not. Put the for loop into main() (and I would recommend you also put N and the vector/student array into main() and everything should work.
Additionally, the compiler is complaining because when you declare Student array[5];or vector<Student> ver[N];it is looking for a default constructor for Student called Student(), which just sets default values for a class. You need to provide this inside the Student class; set the id to some value that can never be an actual student ID, something like -1.

主要问题是您试图在全局范围内执行 for 循环。在函数之外定义和初始化变量是可以接受的,但使用 for 循环或赋值运算符则不然。将 for 循环放入 main() (我建议您也将 N 和 vector/student 数组放入 main() 中,一切都应该正常工作。
此外,编译器正在抱怨,因为当您声明Student array[5];vector<Student> ver[N];正在寻找默认构造函数时对于名为 Student() 的 Student,它只是为类设置默认值。您需要在 Student 类中提供它;将 id 设置为某个永远不可能是实际学生 ID 的值,例如 -1。

回答by Alexey Teplyakov

Option #1:

选项1:

You should replace vector <Student> ver[N]with vector<Student> ver(N)

你应该vector <Student> ver[N]vector<Student> ver(N)

The std::vector is a class, that represents the vector by himself, you shouldn't create an array of vectors, you should just pass N(vector size) to it's constructor. Check this link

std::vector 是一个类,它自己代表向量,你不应该创建一个向量数组,你应该只将 N(vector size) 传递给它的构造函数。检查此链接

Option #2:

选项#2:

Student ver[N];

is incorrect, since the Default Constructor Student() is invoked N times, but you haven't implement it. So you have to use array initilizer Student ver[5] = {1, 2, 3, 4, 5}or implement the default constructor explicitly.

不正确,因为默认构造函数 Student() 被调用 N 次,但您还没有实现它。因此,您必须使用数组初始化程序Student ver[5] = {1, 2, 3, 4, 5}或显式实现默认构造函数。

And of course - the "for" loop has to be used inside function body.

当然 - 必须在函数体内使用“for”循环。

回答by Thomas Benard

This is actually not linked at all with vectors. You just need to move your "for" statement into your main

这实际上与向量根本没有联系。你只需要将你的“for”语句移到你的主要

回答by Van N Tran

#include<iostream>

using namespace std;

class Student
{
    private:
    int id;

    public:
    // Mutator
    void setId(int i){
    id = i;
    }
    // Accessor
    int getId()const{
    return id;}
};

int main()
{
    const unsigned int N = 5;
    Student ver[N];   // Define instances as an array 
    // of the Student class

    int idStudent[N] = { 11, 32, 37, 4, 50};  // Create 
    // one dimensional array with N elements of the 
    // student ID

    for(unsigned int i = 0; i < N; i++ ){ // Assign 
    //student ID for each object of the class
    ver[i].setId(idStudent[i]);}

    cout<< "Hello, This is a code to learn classes : "
    << endl << endl; // Display the student ID

    for(unsigned int i = 0; i < N; i++ ){
    cout<< "Student ID #"  << i+1 << " of "
    << N << " : " << ver[i].getId() << endl;}

    return 0;

}

回答by Van N Tran

The solution to the question asked is to create an array of instances of the Student class as Student ver[N]. Next, using the mutator function, setID(int i) to assign the elements from a given student ID in array format ( int idStudent[N] = { 11, 32, 37, 4, 50};) to each perspective instance of the Student class: ver[i].setId(idStudent[i]) and for loop to finish the job.

所问问题的解决方案是将 Student 类的实例数组创建为 Student ver[N]。接下来,使用 mutator 函数 setID(int i) 以数组格式 ( int idStudent[N] = { 11, 32, 37, 4, 50};) 将给定学生 ID 中的元素分配给每个透视图实例学生类: ver[i].setId(idStudent[i]) 和 for 循环来完成工作。

Last, using the accessor function, ver[i].getID() and the for loop to display the info.

最后,使用访问器函数 ver[i].getID() 和 for 循环来显示信息。