转换为非标量类型请求

问题描述:

即时通讯编程新手,但是我已经在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]并且输入将指向相同的对象?

感谢您的帮助!

new T成功调用返回指向一个动态分配的T对象,所以你正试图从一个指针实例化一个studentstudent这里:

student input= new student; 

你只需要

student input; 

当你做

students[0]=input; 

您正在将input的值分配到位于students[0]中的student实例中。所以students[0]input将是不同的对象。

+0

真棒,清除它给我。再次感谢。 :D还要感谢所有其他答案。 – 2013-05-08 15:45:41

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

student input; 
// fill "input" with data