【问题标题】:C++ Using classes with boost::lexical_castC++ 使用带有 boost::lexical_cast 的类
【发布时间】:2012-04-30 11:24:43
【问题描述】:

我想将我的 Test 类与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 并得到了相同的结果!

【问题讨论】:

  • 有趣的问题,目前还没有找到真正的答案。看起来流有问题: 1. 因为当它进入流运算符时,只有 a 得到更新,b 没有。我添加了另一个字符串来检查空间是否被错误解释,但即使是字符串也没有更新。 2.当你离开操作员时它会抛出,它会检查我不明白的东西然后决定抛出。
  • 您可能应该使用默认构造函数、复制构造函数和析构函数的默认版本,而不是自己定义它们:编译器将为您生成它们(并且在您的情况下会更正确地生成它们)复制构造函数(参见this faq)。

标签: c++ boost lexical-cast


【解决方案1】:

您的问题来自boost::lexical_cast 不会忽略输入中的空格(它取消设置输入流的skipws 标志)。

解决方案是在提取运算符中自己设置标志,或者只跳过一个字符。实际上,提取运算符应该反映插入运算符:由于您在输出Test 实例时明确放置了一个空格,因此您应该在提取实例时明确读取该空格。

This thread 讨论主题,推荐的解决方案是:

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;
} 

【讨论】:

  • +1:我自己在搜索到底发生了什么 10 分钟后才发现它......
  • 成功了,谢谢!但他们为什么这样做呢?我刚刚发现boost::lexical_cast&lt;int&gt;(" 123") 抛出了同样的异常!
  • Boost 论坛上已经详细讨论了这个问题。 This thread 在这方面相当有趣。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-11-16
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多