C++ 多类型对象的想法

C++ Multitype object idea

本文关键字:对象 多类型 C++      更新时间:2023-10-16

我的程序需要大量的ANSI<=>UNICODE对话,所以我想到了创建多类型对象的想法,它将比addination函数和很多new/delete更容易转换所有东西。伪代码:

class CWchar // char based
{
public:
    public static implicit operator wchar_t*(CWchar cw)
    {
        // converting cw.data to wchar_t
        // up to U+FFFF conversion needed
    }
    public static implicit operator char*(CWchar cw)
    {
        return cw.data;
    }
    CWchar& CWchar::operator=(const char* c)
    {
        data = *c; 
        return *this;
    }
    CWchar& CWchar::operator=(const wchar_t* c)
    {
        //conversion to char* ...
        return *this;
    }
    // add some smart pointers, garbage collector, and leave delete
private:
    char* data;
}

这真的值得编码还是我应该考虑另一种解决方案?也许已经完成了项目?或者也许我错了,这个想法很糟糕?谢谢

这听起来很像编解码器。 这允许您在 Char* 和多字节 wchar_t* 流之间进行转换。 这是标准库的一部分。 Stroustrup的《C++编程语言》第三版对此有一个很好的附录。