class CTurist
{
private:
string name;
string country;
int age;
public:
CTurist()
{
name = "";
country = "";
age = 0;
}
CTurist(string n, string c, int a)
{
name = n;
country = c;
age = a;
}
CTurist(const CTurist &t)
{
name = t.name;
country = t.country;
age = t.age;
}
string get_name()
{
return name;
}
string get_country()
{
return country;
}
int get_age()
{
return age;
}
void set_name(string n)
{
name = n;
}
void set_country(string c)
{
country = c;
}
void set_age(int a)
{
age = a;
}
bool operator<(CTurist& t)
{
return this->age < t.age;
}
friend istream& operator >> (istream& istr, CTurist& t)
{
istr >> t.name >> t.country >> t.age;
return istr;
}
friend ostream& operator<<(ostream& ostr, const CTurist& t)
{
ostr << "\nName: " << t.name << ", country: " << t.country << ", age: " << t.age;
return ostr;
}
};
class CHotel
{
private:
string hotel_name;
int num_beds;
double aver_price;
list<list<CTurist>>l;
public:
CHotel()
{
hotel_name = "";
num_beds = 0;
aver_price = 0;
}
CHotel(string hn, int nb, double ap, list<list<CTurist>>&lis)
{
hotel_name = hn;
num_beds = nb;
aver_price = ap;
l = lis;
}
CHotel(const CHotel& h)
{
hotel_name = h.hotel_name;
num_beds = h.num_beds;
aver_price = h.aver_price;
}
string get_hotel_name()
{
return hotel_name;
}
int get_num_beds()
{
return num_beds;
}
double get_aver_price()
{
return aver_price;
}
list<list<CTurist>> get_list_name() {
return l;
}
void set_hotel_name(string hn)
{
hotel_name = hn;
}
void set_num_beds(int nb)
{
num_beds = nb;
}
void set_aver_price(double ap)
{
aver_price = ap;
}
bool operator<(CHotel& h)
{
return this->aver_price < h.aver_price;
}
friend ostream& operator<<(ostream& ostr, const CHotel& h)
{
ostr << "Hotel name: " << h.hotel_name << ", number of beds: " << h.num_beds << ", average price: " << h.aver_price;
for(list<list<CTurist>>::iterator itr=h.l.begin();itr!=h.l.end();itr++)
{
for (list<CTurist>::iterator it = itr->begin(); it != itr->end(); it++)
ostr << *it;
}
return ostr;
}
}
如您所见,我有CTurist和CHotel这两个类。第一个的一切都可以,但第二个问题来了。我正在尝试让Cstream类工作的ostream运算符。其他所有工作都正常,但是只有这个操作员才是问题。我敢肯定这是因为嵌套列表cuz对我来说是新的,也许我有点不对劲。
<br>And this is the error when im trying to debug it.It sure is from this nested list.
error C2440: 'initializing': cannot convert from 'std::_List_const_iterator<std::_List_val<std::_List_simple_types<_Ty>>>' to 'std::_List_iterator<std::_List_val<std::_List_simple_types<_Ty>>>' 1> with 1> [ 1> _Ty=std::list<CTurist,std::allocator<CTurist>> 1> ]
由于h
是const CHotel&
,因此需要const_iterator
:
for (list<list<CTurist>>::const_iterator itr=h.l.begin();itr!=h.l.end();itr++)
{
for (list<CTurist>::const_iterator it = itr->begin(); it != itr->end(); it++)
ostr << *it;
}
或直接使用for range:
for (const auto& turists : h.l)
{
for (const auto& turist : turists)
ostr << turist;
}