クラスのクラスboost::lexical_cast
を使用したいと思います。私はoperator<<
とoperator>>
をオーバーロードしましたが、ランタイムエラーが発生します。ここで
が私のコードです:
C++ boost :: lexical_castでクラスを使用する
#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を使用しています。しかし、私はグラムでのFedora 16を試してみました++と同じ結果を持っています!
興味深い質問を、これまでの本当の答えを見つけることができません。ストリームに何か問題があるように見えます:1.ストリーム演算子に入ると、更新されるだけです.bは更新されません。スペースがひどく解釈されたかどうかをチェックするために別の文字列を追加しましたが、文字列も更新されませんでした。 2.オペレーターから出るときにスローし、私が理解できないものをチェックして投げようとする。 – Klaim
おそらくデフォルトのコンストラクタであるコピーコンストラクタとデストラクタを自分で定義するのではなく、デフォルトのコンストラクタを使うべきです:コンパイラはそれらを生成します(コンストラクタをコピーする場合はもっと正確に行います(see this faq ](http://stackoverflow.com/q/4172722/20984)) –