可以结构包含参数

Could Structure contains parameters?

本文关键字:参数 包含 结构      更新时间:2023-10-16
struct Student s1, s2, s3, s4;
Student(&s1, "Kim", "001");

就像上面的代码一样,如果我将结构"学生"声明为

struct Student
{
std::string Name;
std::string Id;
};

我可以调用像"学生(&s1, "Kim","001"(;这样的参数吗?如何在结构中使用该参数?

您需要

struct添加一个构造函数,该构造函数将要初始化的数据作为参数。然后让构造函数初始化成员变量。

例如:

struct Student
{
    Student(const std::string& name, const std::string& id)
    : Name(name), Id(id) { }
    std::string Name;
    std::string Id;
};

然后你可以做:

Student s1("Foo", "Bar");

或者只使用聚合初始化:

Student s1{"Foo", "Bar};

像这样

Student s1;
s1 = {"Kim", "001"};

或者更简单地说(因为您应该更喜欢初始化而不是赋值(。

Student s1{"Kim", "001"};

不是这样工作的,你应该开始阅读C++的OO编程,这里有一个简短的介绍:

//this is a struct, so all members of the struct are public for standart, this means 
//you can access them from anywhere out of the class
struct Student{
    string Name;
    string Id;
    //now you defined all the member variables, now you need to define a rule, what 
    //happens when you initialize a object, a constructor
    //A Construcot always has the Name of the struct in this case it`s 
    //"Student", The parameters of the function can be choosen freely
    //with the ":" you start to initialize all members, you could also do 
    //this in the brackets.
    Student(string tmp_Name, string tmp_Id)
    : Name(tmp_Name), Id(tmp_Id) { }
}
//now you can do this
int main(){
    Student AStudent("Clara", "1234");
}
这不是

您在C++中初始化成员的方式。struct需要具有构造函数来初始化成员。这是你这样做的方式:

struct Student
{
  Student (std::string name_, std::string id_)
    : name(std::move(name_))
    , id(std::move(id_))
  { }
  std::string name;
  std::string id;
};

这就是初始化类型为 Student 的对象的方式

int main()
{
  struct Student s1("Kim", "001");
}
相关文章: