gpt4 book ai didi

c++ - 重载 << 运算符来存储数据

转载 作者:行者123 更新时间:2023-11-28 08:07:13 25 4
gpt4 key购买 nike

首先,我一直在四处寻找我的特定问题,但我还没有找到任何答案。所以,我想做的是重载 <<运算符(operator),以便我可以做:

myObj = new MyObj();
unsigned int v = 2;
myObj << v;

请记住,使用此类可以做到这一点:

class MyObj{
private:
char *data;
int count;

public:
MyObj(){ data = new char[64]; count = 0; }
//This "is" the overloaded << method
template <typename T>
T& operator<<(T val){
*(T*)(data + count) = val;
count += sizeof(T);
}
}

效果应该和这个一样(假设data是公共(public)属性):

myObj << v;

应该是一样的

*(unsigned int*)(myObj.data + myObj.count) = v;
myObj.count += sizeof(v);

关于如何做的任何想法?我只找到过载 I/O 或位运算符的方法,但诸如此类。

谢谢!

最佳答案

如果我没理解错的话,你有

MyObj *myObj;
......
myObj = new MyObj();
unsigned int v = 2;
myObj << v;

能够使用<<像那样,你通常有:

MyObj myObj;
......
unsigned int v = 2;
myObj << v;

或者你可以使用:

myObj = new MyObj();
unsigned int v = 2;
(*myObj) << v;

如果你想写出像myObj << u << v这样的代码,你还需要:

....
template <typename T>
MyObj& operator<<(T val){
*(T*)(data + count) = val;
count += sizeof(T);
return *this;
}
....

关于c++ - 重载 << 运算符来存储数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10067000/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com