通过重载=运算符从std::String创建String对象

Create String object from std::string by overloading = operator

本文关键字:String 创建 对象 std 重载 运算符      更新时间:2023-10-16

我尝试了几个选项,但我的编译器没有发现运算符重载或其他问题。我使用XCode 4.5.2和默认的Apple LLVM编译器4.1。

我得到的错误是:Assigning to 'cocos2d::CCString *' from incompatible type 'const char [5]'

在这些线路上:

CCString *s_piece__locks = "TEST";
cocos2d::CCString *s_piece__locks2 = "TEST";

我的.h代码:

CCString& operator= (const std::string& str);
//    CCString& operator= (const char* str);  // this doesn't work either
const CCString& operator = (const char *);

我的.cpp代码(即使这是无关的(:

CCString& CCString::operator= (const std::string& str)
{
    m_sString = CCString::create(str)->m_sString;
    return *this;
}
const CCString& CCString :: operator = (const char* str)
{
    m_sString = CCString::create(str)->m_sString;
    return *this;
}

非常感谢您的帮助,谢谢!

错误消息Assigning to 'cocos2d::CCString *' from incompatible type 'const char [5]'表明您正在为指向cocos2d::CCString的指针分配一个char数组。

这应该有效:

char bar[] = "ABCD";
cocos2d::CCString foo;
foo = bar;
CCString *s_piece__locks = "TEST";
cocos2d::CCString *s_piece__locks2 = "TEST";

这到底是怎么回事?声明指针不会生成除指针本身之外的任何对象。因此,基本上,为了"工作",需要已经有另一个CCString对象,它恰好代表字符串"TEST"。但即使给出了这个,C++怎么知道该指向哪一个呢?它需要在某种例如散列映射中查找"TEST"

这些都没有任何意义。将代码更改为任一

  • 直接使用堆栈上的对象:

    cocos2d::CCString s_piece;
    s_piece = "TEST";
    
  • 将新内容分配给位于其他位置的对象。对此,您通常会使用参考,例如

    void assign_test_to(cocos2d::CCString& target) {
      target = "TEST";
    }
    

    也可以使用指针

    void assign_test_to_ptr(cocos2d::CCString* target) {
      *target = "TEST";
    }
    

    但除非你有特定的理由,否则不要这样做。

原则上,还有另一种可能性:

cocos2d::CCString* s_piece_locks = new CCString;
*s_piece_locks = "TEST";

但您需要避免这种情况,因为它很容易导致内存泄漏。可以

std::unique_ptr<cocos2d::CCString> s_piece_locks = new CCString;
*s_piece_locks = "TEST";