您可以使用相同的方式打印lastname
,您可以打印firstname
。如果在類的成員函數打印出來,然後你可以這樣做:
std::cout <<firstname <<" " <<lastname << std::endl;
如果你已經寫了一些get
功能,你從類的非成員函數打印出來,然後你可以這樣做:
student s;
//...
std::cout <<s.getFirstname() <<" " <<s.getLastname() << std::endl;
您還可以添加operator<<
友元函數的類,如:
class student{
private :
string firstname;
string lastname;
// some other variables //etc...
public:
// some functions here ....
friend std::ostream& operator<<(std::ostream & out, const student &s)
{
return out << s.firstname <<" " <<s.lastname;
}
};
然後做到這一點:
std::list<student> students;
//...
for(std::list<student>::iterator it = students.begin(); it != students.end(); it++)
{
std::cout << *it << std::endl;
}
你甚至可以這樣做:
student s;
//...
std::cout << s << std::endl; //it prints firstname and lastname by calling operator<<
什麼是列表?一個std :: list? – Klaim
爲什麼你不能像姓名一樣對姓氏做同樣的事情? –