可以结构包含参数
Could Structure contains parameters?
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");
}
相关文章:
- 表达式 SFINAE:如何根据类型是否包含具有一个或多个参数的函数来选择模板版本
- 读取大文件(>2GB)(文本文件包含以太网数据)并通过不同参数随机访问数据的最佳方法是什么?
- 通过零参数构造函数创建的 glm::mat4 应该包含哪些值?
- 将 C# 对象(包含静态对象成员)作为参数传递给 C++/CLI 程序
- C ++引用函数参数似乎包含原始对象的副本,而不是充当"real reference"
- 生成包含给定类型的 N 个参数的可变参数列表的最佳方法?
- 为什么我应该在scanf()-家族成员中包含一个长度修饰符作为参数?有什么好处?使用长度修改器进行扫描的作用
- 如何将枚举类作为类模板参数包含在内?
- C/C++ 包含点的宏参数(成员访问运算符)
- 包含可变参数包的第一个可转换类型的别名的结构
- C 函数调用包装器包含类成员功能作为模板参数
- 为什么我们可以创建一个模板类结构,其中包含许多与声明结构时指定的参数不同的参数
- 传递多个参数的功能,该函数将类包含到其他函数
- 可以使用默认参数复制包含 lambda 的 std::函数吗?
- 定义的参数在以下包含的标头 [AVR C++] 中不可见
- C++添加到包含 char[] 作为参数的链表中
- 函数参数包含完整的函数
- c++主函数,如果命令行参数包含*,argc值会很奇怪
- C++当参数包含 std::function 时,模板参数推断失败并出现错误"candidate template ignored"...为什么?
- c++的第二周,如果输入参数包含alpha字符,则需要返回错误