再c++中,如果使用了string在一个结构体或者类里面来创建了一个变量,则需要对它进行初始化。下面是完整的代码:
#include"iostream"
#include"cstring"
using namespace std;
struct Node
{
string ID;
string Stu;
int data;
Node (const string & id, const string & stu)
:ID(id), Stu(stu)
{}
};
class Stu
{
private:
Node* phead;
public:
Stu();
void Test(string ID, string Stu);
};
Stu::Stu()
{
phead = (Node*)malloc(sizeof(Node));
}
void Stu::Test(string ID, string Stu)
{
Node* newnode = new Node (ID, Stu);
newnode->ID = ID;
newnode->Stu = Stu;
//...
}
这里在结构体中要增加一个构造函数,用于在使用结构体创建一个对象的时候,能够对里面的string类型数据进行初始化。
Node (const string & id, const string & stu)
:ID(id), Stu(stu)
{}
这个就是构造函数,里面用const string 接受传来的值,然后访问列表给结构体中的成员进行赋值。(" : "是用来访问列表的)。
在创建新的结构体对象的时候,这里要用new来开辟内存,这样才能进行赋值
Node* newnode = new Node (ID, Stu);
这里在用new开辟的时候,传入了ID 和 Stu 给构造函数,构造函数在对里面的对象进行初始化。这样才有下面的赋值操作。