2017-04-04 260 views
0

到目前爲止,我已經定義了一個簡單的類...C++輸出的對象所有成員

class person { 
public: 
    string firstname; 
    string lastname; 
    string age; 
    string pstcode; 
}; 

...然後加一些成員和值命名爲「比爾」的對象......

int main() { 
    person bill; 
    bill.firstname = "Bill"; 
    bill.lastname = "Smith"; 
    bill.age = "24"; 
    bill.pstcode = "OX29 8DJ"; 
} 

但是,您會如何輸出所有這些值?你會使用for循環遍歷每個成員嗎?

+3

嗯,你可能會爲您的課程重載'operator <<'。 – NathanOliver

+2

定義_simply_。你不能循環它們,因爲成員字段不是數組。儘管你可以重載'operator <<'。 –

+1

C++沒有本地反射,因此您需要手動「遍歷」類的成員(某些庫允許某種反射)。 – Jarod42

回答

0

簡單地說,你輸出的每個元素使用ostream

class Person 
{ 
public: 
    void Print_As_CSV(std::ostream& output) 
    { 
     output << firstname << ","; 
     output << lastname << ","; 
     output << age  << ","; 
     output << pstcode << "\n"; 
    } 
    string firstname; 
    string lastname; 
    string age; 
    string pstcode; 
}; 

有可能是印刷的不同的方法,這就是爲什麼我沒有超載operator <<。例如,每行一個數據成員將是另一種流行的情況。

編輯1:爲什麼不循環?
class有單獨的字段,這就是爲什麼你不能迭代成員。

如果要迭代器或遍歷成員,則必須爲您的類使用迭代器或使用容器(如std::vector)提供迭代。

0

我通常會覆蓋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"; 
}