要求转换为非标量类型

时间:2013-05-08 15:31:25

标签: c++

我是c ++编程的新手,但我在java中做了一些编程,所以我对OO编程并不是全新的。

我要做的是创建结构,然后是该结构的对象数组。我试图保持该数组总是排序(使用新手排序),所以我做的是定义结构,然后创建该结构的数组[50],并帮助该结构的变量。然后每个新的不同变量的条目(名称,姓氏,等级等),我从用户输入帮助变量。然后,当用户完成在辅助变量中键入所有数据时,我继续并找出该对象放在数组中的什么位置。

以下是示例代码,尽量保持尽可能简单。

struct student {
    //declaring variables that student should have
};

student students[50];
int numOfStud=0;

while (a=='y' && numofStud<50) { //a=='y' just means user wants to add more students
    student input= new student;
            //adding various data to student     
            //adding input into an array of students using variation of insertion sort algorithm
cout << "want to add more students?";
cin >> a;
}

当我尝试编译时,我在student input= new student收到错误。所以我现在有点困惑。

偏离主题:我还有一个问题,例如当你做students[0]=input;我在这里创建另一个对象副本时会发生什么,或者我只是创建另一个指针(就像在java中),因此我都是学生[0]并且输入将指向同一个对象?

感谢您的帮助!

2 个答案:

答案 0 :(得分:6)

成功调用new T会返回一个指向动态分配的T对象的指针,因此您尝试从指向student的指针实例化student:< / p>

student input= new student;

你只需要

student input;

当你这样做时

students[0]=input;

您要将input的值分配到位于student的{​​{1}}实例中。因此students[0]students[0]将是不同的对象。

答案 1 :(得分:2)

new关键字用于使用指针在上分配内存。你只需要

 student input;
 // fill "input" with data