【问题标题】:Operator overloading without explicit type casting没有显式类型转换的运算符重载
【发布时间】:2013-04-29 16:48:21
【问题描述】:

出于练习目的,我尝试制作自己的小型字符串类。我想重载 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;
}

【问题讨论】:

  • 欢迎来到 SO。您可能希望在字符串类中包含相关的运算符重载代码,以及如何尝试使用它的示例,以及您所看到的行为。否则很难回答你的问题;这通常会导致问题被关闭。
  • 也许我遗漏了一些东西,但您希望您的操作员可以让对象本身为指向对象的指针工作

标签: c++ string class operator-keyword


【解决方案1】:

首先,如果您在 Windows 中工作,CString 是 ATL/MFC 中的一个类。为自己的类重用同名是不礼貌的。

如果不是,您应该为MessageBox 提供签名。

我假设您在 Windows 世界中工作。

您的问题是CString*CString 不同。您定义了一个运算符来将CString 转换为wchar_t const*。毫不奇怪,这不适用于CString*

helloWorld 的定义更改为CString helloWorld = CString(L"Test 123");——没有new,没有指针——你的代码就可以工作了。

另外,您所做的显式转换会导致未定义的行为,因为它将指向对象的指针重新解释为指向字符缓冲区的指针。这是使用 C 风格转换是一个坏主意的众多原因之一,因为重新解释转换和静态转换之间的区别需要大量上下文。要查看错误,请将您的 MessageBox 调用更改为 MessageBox( NULL, static_cast<const wchar_t*>(helloWorld), L"", MB_OK); 具有显式强制转换的代码是否曾经运行并打印任何合理的内容?

如果您确实必须将helloWorld 放在免费存储中,请在使用它时取消引用它(在隐式和显式转换情况下)。即,将helloWorld 的使用替换为*helloWorld。我建议不要这样做——没有充分的理由将此特定实例存储在免费商店中。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-11-21
    • 1970-01-01
    • 2011-01-15
    • 2012-01-25
    • 1970-01-01
    • 1970-01-01
    • 2014-02-02
    相关资源
    最近更新 更多