将对象嵌入到链表中

Embedding object to a linked list c++

本文关键字:链表 对象      更新时间:2023-10-16

我正在尝试添加一个对象到链表。我的程序的想法是做一个学生信息系统。在这个学生信息系统中,当有一个新的学生条目时,将创建一个类的新对象,该对象将是链表中新节点的信息。换句话说,对象将是链表节点的信息字段。我已经尝试了这个程序,但是得到一个错误。

#include<iostream.h>
class result
{
    int age;
    char name[30];
    float marks;
public:
    void ret(int a, float m)
    {
        age = a;
        marks = m;
    }
};
struct node
{
    result info;
    struct node *next;
};

void main()
{
    struct node *h, *t;
    int g;
    float ma;
    cout<<"Enter age , name , marksn";
    cin>>g;
    cin>>ma;
    result ob;
    h = NULL;
    t = new node;
    t->info = ob.ret(g,ma);
    t->next = NULL;
    h = t;
    cout<<t->info;
}

错误是:

1)不允许的类型2)违规结构操作

ret是返回voidresult的成员。我猜你的意思是让result的构造函数有两个参数。这就是你要做的

class result
{
 int age;
 char name[30];
 float marks;
 public:
 result(){}
 result(int a, float m)
 {
  age = a;
  marks = m;
 }
};

并将t->info = ob.ret(g,ma);更改为t->info = result(g, ma);