如何将 CString 传递给格式字符串 %s?

class MyString
{
public:
    MyString(const std::wstring& s2)
    {
        s = s2;
    }

    operator LPCWSTR() const
    {
        return s.c_str();
    }
private:
    std::wstring s;
};

int _tmain(int argc, _TCHAR* argv[])
{
    MyString s = L"MyString";
    CStringW cstring = L"CString";
    wprintf(L"%s
", (LPCWSTR)cstring); // Okay. Becase it has an operator LPCWSTR()
    wprintf(L"%s
", cstring); // Okay, fine. But how?        
    wprintf(L"%s
", (LPCWSTR)s); // Okay. fine.
    wprintf(L"%s
", s); // Doesn't work. Why? It prints gabage string like "?."
    return 0;
}

如何将 CString 传递给格式字符串 %s?

How can CString be passed to format string %s?

顺便说一句,MSDN 说(很奇怪)

By the way, MSDN says(it's weird)

在可变参数函数中使用 CString 对象
将 CString 显式转换为 LPCTSTR 字符串,如下所示:

To use a CString object in a variable argument function
Explicitly cast the CString to an LPCTSTR string, as shown here:

CString kindOfFruit = "bananas";
int      howmany = 25;
printf( "You have %d %s
", howmany, (LPCTSTR)kindOfFruit ); 

推荐答案

CString 是专门设计的,它只包含一个指向缓冲区类中字符串数据的指针.当按值传递给 printf 时,当看到格式字符串中的%s"时,它将被视为指针.

CString is specifically designed such that it only contains a pointer that points to the string data in a buffer class. When passed by value to printf it will be treated as a pointer when seeing the "%s" in the format string.

它最初只是碰巧与 printf 一起工作,但后来被保留为类接口的一部分.

It originally just happened to work with printf by chance, but this has later been kept as part of the class interface.

这篇文章是基于早已退休的 MS 文档,所以我无法链接到他们承诺他们将继续完成这项工作.

This post is based on MS documentation long since retired, so I cannot link to their promise that they will continue to make this work.

但是,在添加更多反对意见之前,还请阅读分享我旧知识的人的这篇博文:

However, before adding more downvotes please also read this blog post from someone sharing my old knowledge:

老大哥帮你

相关文章