gpt4 book ai didi

C++ 如何将任何类(自定义)对象转换为 vector

转载 作者:塔克拉玛干 更新时间:2023-11-03 07:42:10 24 4
gpt4 key购买 nike

我定义了自己的类:

class Rectangle {
int width;
int height;
};

我想将任何此类类对象转换为 vector<unsigned char> .我尝试针对特定类型执行此操作,然后针对任何类型执行此操作:

template< typename T > std::vector< byte, sizeof(T) >  to_bytes( const T& object ) {
std::vector< byte, sizeof(T) > bytes ;
const byte* begin = reinterpret_cast< const byte* >(std::addressof(object)) ;
const byte* end = begin + sizeof(T) ;
std::copy( begin, end, std::begin(bytes) ) ;
return bytes ;
}

但这仅对特定的 type 有效在 C++ 中。如何转换我的 Rectangle类,或与此相关的任何用户定义类 vector<unsigned char>

最佳答案

您可以通过在 Rectangle 类中进行用户定义的类型转换来做到这一点:

explicit operator vector<unsigned char>() const {
// Do something here
}

希望这对您有所帮助。

关于C++ 如何将任何类(自定义)对象转换为 vector <unsigned char>,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47506030/

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