簡體   English   中英

C ++使用帶有boost :: lexical_cast的類

[英]C++ Using classes with boost::lexical_cast

我想在boost::lexical_cast使用我的Test類。 我重載了operator<<operator>>但它給了我運行時錯誤。
這是我的代碼:

#include <iostream>
#include <boost/lexical_cast.hpp>
using namespace std;

class Test {
    int a, b;
public:
    Test() { }
    Test(const Test &test) {
        a = test.a;
        b = test.b;
    }
    ~Test() { }

    void print() {
        cout << "A = " << a << endl;
        cout << "B = " << b << endl;
    }

    friend istream& operator>> (istream &input, Test &test) {
        input >> test.a >> test.b;
        return input;
    }

    friend ostream& operator<< (ostream &output, const Test &test) {
        output << test.a << test.b;
        return output;
    }
};

int main() {
    try {
        Test test = boost::lexical_cast<Test>("10 2");
    } catch(std::exception &e) {
        cout << e.what() << endl;
    }
    return 0;
}

輸出:

bad lexical cast: source type value could not be interpreted as target

順便說一句,我正在使用Visual Studio 2010但我已經嘗試使用g ++的Fedora 16並得到了相同的結果!

你的問題來自於boost::lexical_cast不會忽略輸入中的空格(它取消設置輸入流的skipws標志)。

解決方案是在提取運算符中自己設置標志,或者只跳過一個字符。 實際上,提取運算符應該鏡像插入運算符:因為在輸出Test實例時明確地放置了空格,所以在提取實例時應該明確地讀取空格。

該主題討論了主題,建議的解決方案是執行以下操作:

friend std::istream& operator>>(std::istream &input, Test &test)
{
    input >> test.a;
    if((input.flags() & std::ios_base::skipws) == 0)
    {
        char whitespace;
        input >> whitespace;
    }
    return input >> test.b;
} 

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM