c++ - 为 Unicode 和 ANSI 重载 toString

标签 c++ unicode overloading

当为一个类实现toString()函数时,我应该同时实现unicode和ascii版本吗?

class MyClass
{
public:

    string toString()
    {
        return "foo";
    }

    // Should the unicode version be implemented aswell?
    wstring toString()
    {
        return L("foo");
    }

};


// Does this suffice?
#ifndef UNICODE
typedef string tstring;
#else
typedef wstring tstring;
#endif

class MyClass
{
public:

    tstring toString()
    {
        return "foo";
    }
};

还有函数重载可以转换成int吗?

class MyClass
{
public:

    // ???
    int operator>>(MyClass& obj)
    {
        return myInt;
    }
private:
    int myInt;
};

最佳答案

很明显,这个问题是关于 Windows 编程的,尽管这并没有反射(reflect)在(我写这篇文章时的当前)标签中。

对于 Windows,您应该使用 wchar_t 类型,而不必费心维护与早期 Windows 版本的兼容性,您(1)甚至无法为现代版本生成可执行文件Visual C++。

就是这样。


<支持> (1) 如果您可以生成 Windows 9x 可执行文件,那么支持旧 Windows 的方法就不会是使用陈旧的 T 东西或直接使用 ANSI 文本,但使用 Microsoft 的 Layer for Unicode 从 2000 年开始,现在已有 15 年了;这顶帽子很老了。

关于c++ - 为 Unicode 和 ANSI 重载 toString,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34247679/

相关文章:

c++ - 是否有标准的memory_resource分配器适配器/包装器?

c++ - 模板的丑陋编译器错误

c++ - 结构的通用类型

php - 为什么 PHP 的 urlencode 使用不同的 URL 编码?

java - 使用可变参数重载

c++ - 为什么 __builtin_popcount 比我自己的位计数函数慢?

JavaScript 相当于 C# 的 Char.IsSymbol

c - 如何使用 '%s' 说明符打印 unicode 字符串?

c++ - 重载 >> 运算符以读取文本文件

c++ - 运算符重载 C++ : write-only version