我试图做的是在流(std :: ostream)中插入一个缓冲区。
这个缓冲区是我班级的一个属性" AcquiSample"
我让这个例子非常简单,让你理解我的问题。
这里是班级的定义:
class AcquiSample
{
public:
IQSample * buffer;
}
这里是struct IQSample的定义:
struct IQSample {
struct {
short val;
}I;
struct {
short val;
}Q;
}
我想要做的是将具有已知大小的缓冲区放入如下的流中:
std::ostream stream;
AcquiSample obj;
stream << obj.buffer->I.val << obj.buffer->I.val;
我认为它没有工作,因为它没有复制数据而是指针地址,我想要的是将整个缓冲区放入此流中,因为我将此流发送到另一个计算机。
如果有人知道该怎么做,我会非常感激。
答案 0 :(得分:2)
实现此目的最惯用的方法是重载插入操作符:
struct IQSample {
struct {
short val;
}I;
struct {
short val;
}Q;
};
std::ostream& operator<<( std::ostream& os, IQSample iqs )
{
return os << iqs.I.val << ' ' << iqs.Q.val; // Don't forget to put white spaces between the numbers!
}
std::istream& operator>>( std::istream& os, IQSample& iqs )
{
return is >> iqs.I.val >> iqs.Q.val;
}
现在
std::ostream stream; // some stream bound to a streambuf who transfers over network
AcquiSample obj;
stream << *obj.buffer;
答案 1 :(得分:1)
也许你正在寻找这样的东西?
std::ostream& operator<<(std::ostream& os, const AcquiSample & sample)
{
//Deserialize your object here, or create methods in AcquiSample for serialization and deserialization.
os << sample.buffer->I.val;
os << sample.buffer->Q.val;
return os;
}
int main(int argc, char **argv) {
std::ostream stream; // Don't forget to initialize the stream.
AcquiSample obj; // Don't forget to set buffer to something!
stream << obj;
}