在C ++中用对象填充列表时出现奇怪的问题? [英] Bizarre issue when populating a list with objects in C++?
问题描述
我创建了一个类Patient
,我想用通过显式构造函数创建的对象填充Patients
列表.但是,当我尝试使用`= {}(初始化列表)填充list<Patient>
时,出现错误Type name is not allowed
.我想问我在做什么错了吗?
I have created a class Patient
and I want to populate a list of Patients
with objects which I have created via the explicit constrctor. However I get an error Type name is not allowed
when I try to populate the list<Patient>
using the `={}(initializer list). I would like to ask what am I doing wrong?
#include "pch.h"
#include <iostream>
#include <string>
#include <list>
using namespace std;
class Patient {
string name;
string birthday;
int visits;
public:
Patient(string n, string b, int v) {
name = n;
birthday = b;
visits = v;
}
};
list<Patient> sp = {
Patient a("I.Petrov", "21.12.02", 4),
Patient b("D.Stoyanov", "12.02.97", 7),
Patient c("K.Dimitrov", "07.08.90", 1)
};
int main()
{
return 0;
}
推荐答案
列表的初始化程序采用一系列表达式,但是您给了它完整的变量声明.那根本就是无效的语法.您只能在函数或命名空间范围内的自由空间"中放置声明,而不能在其他语句中放置声明(出于此答案的目的,我们将忽略条件语句的乐趣).
The list's initializer takes a sequence of expressions, but you've given it full variable declarations instead. That's simply not valid syntax. You can only put declarations in "free space" in a function or at namespace scope, not inside another statement (we'll ignore the joys of conditionals for the purpose of this answer).
您可能打算创建一些临时对象:
You probably intended to create some temporaries instead:
list<Patient> sp = {
Patient("I.Petrov", "21.12.02", 4),
Patient("D.Stoyanov", "12.02.97", 7),
Patient("K.Dimitrov", "07.08.90", 1)
};
但是我将其写为:
std::list<Patient> sp{
{"I.Petrov", "21.12.02", 4},
{"D.Stoyanov", "12.02.97", 7},
{"K.Dimitrov", "07.08.90", 1}
};
这篇关于在C ++中用对象填充列表时出现奇怪的问题?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!