9

我想将我的测试类与boost::lexical_cast. 我已经重载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 并得到了相同的结果!

4

1 回答 1

8

Your problem comes from the fact that boost::lexical_cast does not ignore whitespaces in the input (it unsets the skipws flag of the input stream).

The solution is to either set the flag yourself in your extraction operator, or just skip one character. Indeed, the extraction operator should mirror the insertion operator: since you explicitely put a space when outputting a Test instance, you should explicitely read the space when extracting an instance.

This thread discusses the subject, and the recommended solution is to do the following:

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;
} 
于 2012-04-30T12:02:37.953 回答