为了练习目的,我尝试制作自己的小型字符串类。我想重载 const wchar_t* 运算符以返回保存在 String 对象中的缓冲区,但是当我实际访问该对象时它失败了。它的转换运算符没有被调用。只有当我通过显式类型转换对象时它才有效(const wchar_t*) mystring
编辑:
// CString.h
class CString {
private:
wchar_t* _string;
void set(const wchar_t text[]);
public:
CString();
CString(const wchar_t text[]);
CString(const CString& text);
~CString();
operator const wchar_t*() const;
};
// CString.cpp
#include "CString.h"
CString::CString() { set(L""); }
CString::CString(const wchar_t text[]) { set(text); }
CString::~CString() { delete[] _string; }
void CString::set(const wchar_t text[]) {
delete[] _string;
_string = new wchar_t[wcslen(text)];
wcscpy(_string, text);
}
CString::operator const wchar_t*() const {
return _string;
}
// main.cpp
int main() {
CString* helloWorld = new CString(L"Test 123");
MessageBox(NULL, helloWorld, L"", MB_OK); // This doesn't work
MessageBox(NULL, (const wchar_t*) helloWorld, L"", MB_OK); // This works, but I don't explicitly want to use the cast everytime.
return 0;
}