【发布时间】: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