2016-12-28 22 views
0

就像我們在CIN使用:如何使用提取操作符從C++中的類的方法中獲取多個值?

cin >> a >> b; 

從輸入流中獲取多個值,並將其插入到多個變量。 我們如何在自己的課堂上實施這種方法?從中獲取多個值。 我想這是發現here

#include <iostream> 
using namespace std; 

class example { 
    friend istream& operator>> (istream& is, example& exam); 
    private: 
     int my = 2; 
     int my2 = 4; 
}; 

istream& operator>> (istream& is, example& exam) { 
    is >> exam.my >> exam.my2; 
    return is; 
} 

int main() { 
    example abc; 
    int s, t; 

    abc >> s >> t; 
    cout << s << t; 
} 

但得到錯誤「不匹配的操作>>(操作數類型是‘例如’和‘廉政’)」

PS:我知道的替代方式,但我想知道這樣做的具體方式,謝謝。

回答

0

您定義的插入運算符與std::istream一起作爲源而不是您自己的類。雖然我認爲你的目標不明智,但你可以爲你的班級創建類似的操作員。您需要一些具有合適狀態的實體,因爲鏈接的操作員應該提取不同的值。

我不會用這個任何類型的生產設立的,但它確實可以做到:

#include <iostream> 
#include <tuple> 
using namespace std; 

template <int Index, typename... T> 
class extractor { 
    std::tuple<T const&...> values; 
public: 
    extractor(std::tuple<T const&...> values): values(values) {} 
    template <typename A> 
    extractor<Index + 1, T...> operator>> (A& arg) { 
     arg = std::get<Index>(values); 
     return extractor<Index + 1, T...>{ values }; 
    } 
}; 

template <typename... T> 
extractor<0, T...> make_extractor(T const&... values) { 
    return extractor<0, T...>(std::tie(values...)); 
} 

class example { 
private: 
    int my = 2; 
    int my2 = 4; 
    double my3 = 3.14; 
public: 
    template <typename A> 
    extractor<0, int, double> operator>> (A& arg) { 
     arg = my; 
     return make_extractor(this->my2, this->my3); 
    } 
}; 

int main() { 
    example abc; 
    int s, t; 
    double x; 

    abc >> s >> t >> x; 
    cout << s << " " << t << " " << x << "\n"; 
} 
+0

非常感謝。我明白這在編程方面不是一個好主意,但我只是有一種渴望知道它並且從一小時開始就在尋找。 –

1

你想從example提取數據到int。相反,您編寫代碼將數據從istream提取到example。這就是爲什麼找不到正確的功能:你沒有寫出一個。

如果你真的想允許abc >> s >> t工作,你將不得不定義一個operator>>(example&, int&)並添加流/遊標語義到你的類,以跟蹤到目前爲止提取的內容的每一步。這聽起來像是比它的價值更麻煩。

相關問題