2015-04-03 157 views
2

我想知道是否有可能過載<< operator需要以兩種方式在類中打印對象。Overload ostream <<運算符

例如,我建立一個多米諾骨牌的遊戲,所以我需要打印我的立方體與數字:[1][6][6][3] 和打印電腦多維數據集:[ ][ ]

+0

IIRC,它*的*重載...所以你想做什麼就很有可能=) – Mints97 2015-04-03 19:37:32

+0

標準使用[流操縱]( http://en.cppreference.com/w/cpp/io/manip)以各種方式打印相同的數據。 – 2015-04-03 19:40:32

+0

哈哈我試圖想辦法,因爲我不知道該怎麼改變函數的參數,因爲它們幾乎相同,只有執行不同:( – imthaking 2015-04-03 19:40:49

回答

3

這裏是超載提取和插入運營商的一個例子:

/* 
    Operator: << 
    This insertion operator outputs the data members of 
    class object instantiation in the format:(x,y) 
    The returning type ostream&, allows 
    you to chain more then one objects to be printed. 
*/ 
ostream& operator<< (ostream& os, class_name& object_name) { 
    return os << '(' << object_name.get_data_memberx() 
      << ',' << object_name.get_data_membery() 
      << ')'; 
} 

/* 
    Operator: >> 
    This extraction operator creates an input stream it 
    inserts to it values for of all the data members of 
    the class passed by reference and returns it. 
    Input format: (x,y) 
*/ 
istream& operator>> (istream& is, class_name& object_name) { 
    char par1, comma, par2; 
    double x, y; 

    is >> par1 >> x >> comma >> y >> par2; 
    // check if any input 
    if(!is) return is; 
    // check for valid input format 
    if (par1 != '(' || comma != ',' || par2 != ')') { 
     // set failbit to indicate invalid input format 
     is.clear(ios_base::failbit); 
     return is; 
    } 
    // assign input values to second argument 
    object_name = class_name(x,y); 
    return is; 
} 

您可以使用上面的示例並修改格式以匹配所需的結果。

+3

這將是一個*插入操作符*。此外,我不認爲這回答瞭如何以兩種方式打印對象: – 2015-04-03 19:43:36

+1

該操作符將對象「插入」到ostream中。提取操作符通常用於'cin' – Carcigenicate 2015-04-03 19:50:16

+0

@Drew Dormann感謝修正。 – Ziezi 2015-04-03 19:50:27

0

< <用於cout的運算符實際上是重載的位運算符,用於獲取此行爲。

我真的不明白你想要達到什麼目的(代碼段會有幫助)。但是,似乎您想要爲ostream和YourClass類型重載< <。你可以有這樣的東西:

void operator<<(ostream str, YourClass cls) { 
    // generate required output 
} 

請注意,這是一個常規函數,只是調用語法不同。

+1

它應該返回'ostream&'不是void – 2015-04-03 19:47:23

+0

但是如果我想另外添加另一個以不同方式打印的重載,那該怎麼辦呢?例如:X = Y = – imthaking 2015-04-03 19:47:46

+0

然後,您返回一個ostream和對該ostream的引用,如@Alejandro Diaz建議。請注意,我的代碼段比您實際需要的指導更多 – Paul92 2015-04-03 19:50:21

2

雖然其他人已經回答瞭如何重載operator<<,但目前還不清楚如何使用兩種不同的格式。我推薦這個:臨時對象。

struct showdomino { 
    domino& d; 
}; 
std::ostream& operator<<(std::ostream& out, showdomino dom) 
{return out << '[' << dom->d.number << ']';} 

struct hidedomino {}; 
std::ostream& operator<<(std::ostream& out, hidedomino dom) 
{return out << "[ ]";} 

然後使用是含糊這樣的:

if (show_it) 
    std::cout << showdomino{d} << '\n'; 
else 
    std::cout << hidedomino{} << '\n'; 
+0

該行是什麼:if(show_it)呢? – imthaking 2015-04-03 20:06:20

+1

這是...成爲我所有代碼中最直接的一行。它只是一個if語句,作爲任何_your_代碼的佔位符。 – 2015-04-03 20:08:39

+0

Ohhhh好的謝謝! – imthaking 2015-04-03 20:10:49