我通常會覆蓋operator <<
,以便我的對象與任何內置對象一樣易於打印。
這裏是重寫operator <<
一種方法:
std::ostream& operator<<(std::ostream& os, const person& p)
{
return os << "("
<< p.lastname << ", "
<< p.firstname << ": "
<< p.age << ", "
<< p.pstcode
<< ")";
}
然後使用它:
std::cout << "Meet my friend, " << bill << "\n";
下面是使用這種技術的一個完整的程序:
#include <iostream>
#include <string>
class person {
public:
std::string firstname;
std::string lastname;
std::string age;
std::string pstcode;
friend std::ostream& operator<<(std::ostream& os, const person& p)
{
return os << "("
<< p.lastname << ", "
<< p.firstname << ": "
<< p.age << ", "
<< p.pstcode
<< ")";
}
};
int main() {
person bill;
bill.firstname = "Bill";
bill.lastname = "Smith";
bill.age = "24";
bill.pstcode = "OX29 8DJ";
std::cout << "Meet my friend, " << bill << "\n";
}
嗯,你可能會爲您的課程重載'operator <<'。 – NathanOliver
定義_simply_。你不能循環它們,因爲成員字段不是數組。儘管你可以重載'operator <<'。 –
C++沒有本地反射,因此您需要手動「遍歷」類的成員(某些庫允許某種反射)。 – Jarod42